0

I developed an input that allows me to paste images inside, using CTRL-V.

I copy an image from the browser using (copy image address), done that, put the mouse in the input and do ctrl-v to paste the image.

I can get the image in base64, is there a way to "draw / transform" that image and place it with a height and width of 600/600?

That is, in the image I receive, I intend it to be 600 in height and width. I have tried to implement some functions using Canvas but without success.

Can someone help me?

DEMO

Code

  @HostListener("paste", ["$event"])

  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData("text");
    console.log(pastedData)
  }

Image

mvp Sets
  • 119
  • 1
  • 3
  • 9

1 Answers1

1

Something like this. You will probably need some sort of resizing tool to prevent image distortion but this is generally the path you want to follow. I highly recommend that you take a look at the resources at the end of this post.

  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData("text");
    console.log(pastedData)
    let canvas = document.createElement("canvas")
    canvas.height = 600
    canvas.width = 600
    let ctx = canvas.getContext("2d")
    let img = new Image()
    img.onload = ()=>{
      ctx.drawImage( img, 0, 0, 600, 600 )
      pastedData = canvas.toDataURL('image/png')
      console.log(pastedData)
    }
    img.src = pastedData
    img.style.height ='600px'//this is not a good way to resize
    img.style.width = '600px'//high chance of distortion
  }

Extra Resources:

Resize tool

Drawing Canvas Images

Michael Artman
  • 319
  • 1
  • 14
  • Thanks for the reply. I intend to send the image to a service, that is, when sending to the service I want the image to be already in a 600x600 dimension, otherwise the image is too small – mvp Sets Feb 27 '20 at 15:07
  • In that case, you will want to dump your base64 string to a canvas, draw the canvas to 600x600 then dump your canvas back into a base64. A good place to start would be https://stackoverflow.com/questions/4409445/base64-png-data-to-html5-canvas – Michael Artman Feb 27 '20 at 15:10
  • I tried this, but when making the console.log from the drawn image, nothing appears to me – mvp Sets Feb 27 '20 at 15:12
  • Okay, I updated my answer. One thing to note is that image resizing can be a bit difficult to do dynamically but I left some extra resources in at the bottom to help you navigate this problem. – Michael Artman Feb 27 '20 at 16:00