basst314 / ngx-webcam

A simple Angular webcam component / pure & minimal, no flash-fallback
https://basst314.github.io/ngx-webcam/?
MIT License
228 stars 104 forks source link

How to obtain image size? #100

Closed cooper-mj closed 3 years ago

cooper-mj commented 3 years ago

@basst314 - first and foremost, thanks for creating this awesome library. I'm using it in a project of mine, and I love it!

I've run into a small issue that I'm hoping you will be able to help me resolve. I am trying to send an image captured from the webcam to a server via an HTTP POST request. As I'm sending the image as a bytes string, however, I'm unable to decode it in the backend without knowing the original height and width of the image. As I see it, there is no attribute height or width attached to the imageData attribute of the webcamImage object.

I tried running this function from another issue (#45) on this repo, to obtain height/width from the image data:

 private imagedata_to_image(imagedata) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  canvas.width = imagedata.width;
  canvas.height = imagedata.height;
  console.log(`Image data height: ${imagedata.height}, Image data width: ${imagedata.width}`);
  ctx.putImageData(imagedata, 0, 0);

  var image = new Image();
  image.src = canvas.toDataURL();
  return image;
}

Although passing in webcamImage.imageData to this function raises an error when it goes to evaluate image data.width.

How might I obtain the dimensions of the image so that I may send the height and width along with the bytes-encoded image?

Thank you!

basst314 commented 3 years ago

Hi @cooper-mj

To access the plain image as base64 data, use „imageAsBase64“ instead of „imageAsDataUrl“. This will return the image as base64 encoded string. When you base64 decode the image on the backend you will end up with the image bytes.

Where do you need the image dimensions?

If you really need them, you can access „webcamImage.imageData“ which gives you access to the canvas image data object which should have width/height information.

Cheers!

cooper-mj commented 3 years ago

Hi @basst314 - thank you so much for the prompt reply! And thank you for pointing out that I should be using the imageAsBase64 encoding.

However, when I go to call webcamImage.imageData.width, I get that it is null - am I making a mistake in this call, or is this how it's supposed to be?

Thank you!

basst314 commented 3 years ago

Hi @cooper-mj

Please check that you set „captureImageData“ to true when embedding the webcam component (see Readme).

Let me know if that helps.

cooper-mj commented 3 years ago

That was it - thank you!!

basst314 commented 3 years ago

Great, thanks for letting me know. I‘m resolving this issue.