Via pure JS, I'm attempting to reorient a JPEG (to 1
) and resize it to certain resolution benchmarks. I'm unable to get the logic right; images produced have the canvas in the right position/dimensions, but the image's aspect ratio messes up and doesn't fit the canvas.
For instance, here's the result of running my code on an image where the orientation had initially been set to 8
:
My code correctly oriented it to 1
, but couldn't fit the image to the canvas' dimensions.
How can I fix my code? Here's what I have:
var max_img_width = 400;
var wranges = [max_img_width, Math.round(0.8*max_img_width), Math.round(0.6*max_img_width),Math.round(0.4*max_img_width),Math.round(0.2*max_img_width)];
function reorient_and_resize(source_img, img_width, img_height, mime_type, orientation){
if (4 < orientation && orientation < 9) {
// switch around height and width
var temp = null;
temp = img_width;
img_width = img_height;
img_height = temp;
}
var new_width = null;
switch (true) {
case img_width < wranges[4]: new_width = wranges[4];break;
case img_width < wranges[3]: new_width = wranges[4];break;
case img_width < wranges[2]: new_width = wranges[3];break;
case img_width < wranges[1]: new_width = wranges[2];break;
case img_width < wranges[0]: new_width = wranges[1];break;
default: new_width = wranges[0];break;
}
var wpercent = (new_width/img_width);
var new_height = Math.round(img_height*wpercent);
var canvas = document.createElement('canvas');
canvas.width = new_width;
canvas.height = new_height;
var ctx = canvas.getContext("2d");
// transform context before drawing image
switch (orientation) {
case 2: ctx.transform(-1, 0, 0, 1, new_width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, new_width, new_height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, new_height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, new_height, 0); break;
case 7: ctx.transform(0, -1, -1, 0, new_height, new_width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, new_width); break;
default: break;
}
ctx.drawImage(source_img, 0, 0, new_width, new_height);
return dataURItoBlob(canvas.toDataURL(mime_type),mime_type);
}
I suspect my canvas transformations aren't working. Please advise.
Note: Let's stick to pure JS for the scope of this question, without recourse to any 3rd party libraries.
The image originally looked as follows. At this point, orientation is 1
. I purposely set its orientation to 8
before testing my algorithm (and thereafter found erroneous results):