Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing photo on a canvas without losing the aspect ratio

Hi all thanks for any help in advance. I am writing a phonegap app and can not get the photo to shrink without either losing the aspect or cropping the image by mistake. In the function below "imageData" is a 64bit string of the photo that the camera took. I can draw the image onto the canvas on my page, but if the picture was taken in landscape then it is smashed together. If i do not scale it either by using the scale function or the drawimage function then i get only the top corner of the photo. A example: i took a photo the image width in the onPhotoDataSuccess function shows it to be 1296px wide, and 968px height. But my canvas on the iPhone is 272px wide (portrait mode). I have tried many different scaling methods on the web and this appears to be the closest by not quite. What am i doing wrong?

 function onPhotoDataSuccess(imageData) 
{
var myImage = new Image();
var thecanvas = document.getElementById("queImg");
var ctx = thecanvas.getContext("2d"); 
myImage.onload = function() 
  { 
    thecanvas.setAttribute('width', '100%');
    thecanvas.setAttribute('height', 'auto');
    ctx.scale((myImage.width * 0.15), (myImage.height * 0.15));  
    ctx.drawImage(myImage, 0, 0);   
    }     

    myImage.src = "data:image/jpeg;base64," + imageData;      
}
like image 780
user852566 Avatar asked Jul 19 '11 18:07

user852566


People also ask

How do I resize an image without changing the aspect ratio?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

How do you keep the aspect ratio of an image in canvas?

drawImage(img, 0, 0); ctx. scale(1 / factor, 1 / factor); This should preserve the aspect ratio.

How do I resize an image in canvas?

Right-click on the image and select Resize Image.... After selecting Resize Image... a dialog will appear that gives you precise control over the size of the image.


1 Answers

Scaling is built in to drawImage.

Don't use setAttribute when dealing with canvas, call canvas.width = 272 instead, and only with whole pixel values.

Here is some working code to get you started:

 function onPhotoDataSuccess(imageData)
{
var myImage = new Image();
var thecanvas = document.getElementById("queImg");
var ctx = thecanvas.getContext("2d");

    myImage.onload = function() {
    ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15);
    }     

    myImage.src = "http://placekitten.com/1296/968";
}


onPhotoDataSuccess(null);

Live example:

http://jsfiddle.net/QBTrg/6/

like image 128
Simon Sarris Avatar answered Nov 15 '22 00:11

Simon Sarris