I am making a client side Drag and Drop file upload script as a bookmarklet. Before uploading I am using the File API to read the images into base64 format and display them as thumbnails.
This is how my thumbnails look like. I want them to look more square but without loosing their aspect ratio. (please ignore progress bar)
This is how I want the thumbnails to be like, they are centered and being cropped based on min(height,width).
Can I do this using javascript only (changing styles via script will do)? Please try to make sure that your solution will fit with base64 images (after the images are read via file API as DATA URL).
I have uploaded these exact set of images here.
Thanks for the help.
Just wanted to share how I resolved my issue. Since I wanted a purely javascript only solution, I used throwaway canvas elements to do the dirty work.
Here is my code for the same:
function resizeImage(url, width, height, callback, file) {
console.log("In_resizeImage");
var sourceImage = new Image();
sourceImage.onload = (function (f) {
return function (evt) {
console.log("In_sourceImage_onload");
console.log("sourceImage.width:" + sourceImage.width);
console.log("sourceImage.height:" + sourceImage.height);
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
if (sourceImage.width == sourceImage.height) {
canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
} else {
minVal = Math.min(sourceImage.width, sourceImage.height);
if (sourceImage.width > sourceImage.height) {
canvas.getContext("2d").drawImage(sourceImage, (sourceImage.width - minVal) / 2, 0, minVal, minVal, 0, 0, width, height);
} else {
canvas.getContext("2d").drawImage(sourceImage, 0, (sourceImage.height - minVal) / 2, minVal, minVal, 0, 0, width, height);
}
}
callback(canvas.toDataURL(), f);
}
})(file);
sourceImage.src = url;
}
I was directly dealing with image files so I was able to use Image object. For others to use, little bit tweaking might be required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With