0

In my webapplication the user can take a photo with the camera on his mobile device. The photo is then displayed in a canvas.

<canvas id="photo" ></canvas>

Now I want to send the photo to a backend server. The best way to do this seems to be encoding the image to a base64 string.

However, I want the photo to always be the same resolution, for example 100 x 100 pixels. Otherwise the base64 string is too big.

I am currently using the second parameter of toDataURL to determine the export quality of the picture. (here 2%).

var base64 = document.getElementById("photo").toDataURL("image/jpeg", 0.02);

This does not seem to be a good way because I don't know the initial resolution of the photo. So I would like to always get the photo in the same resolution. How to achieve this?

Anonymoose
  • 2,389
  • 6
  • 36
  • 69
  • I'm wondering if this question might give you part of your answer, regarding resizing images? http://stackoverflow.com/questions/961913/image-resize-before-upload – niaccurshi Jan 30 '14 at 10:07

1 Answers1

0

You could use an invisible background canvas with a size of 100x100 and copy the image from the photo-canvas to it. The drawImage function allows you to specify a size for the destination rectangle. When it's not the same as the source rectangle, the content will be scaled:

// Create a temporary, invisible 100x100 canvas
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = 100;
tmpCanvas.height = 100;
var tmpContext = canvas.getContext('2d');

// copy the content of the photo-canvas to the temp canvas rescaled
var photoCanvas = document.getElementById("photo");
tmpContext.drawImage(photoCanvas,                                // source
                    0, 0, photoCanvas.width, photoCanvas.height, // source rect
                    0, 0, 100, 100                               // destination rect
                   );

// get data-url of temporary canvas
var base64 = tmpCanvas.toDataURL("image/jpeg");

But keep in mind that when the source-canvas isn't rectangular, the aspect ratio won't be preserved. When you don't want this, there are different ways to deal with this issue, like cropping or adding a border. Most of these would be implemented by choosing different source- or destination rectangles in the drawImage call.

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Just nitpicking, but source and dest rects are not really necessary here, just use: `tmpContext.drawImage(photoCanvas, 0, 0, 100, 100);` –  Jan 31 '14 at 08:50