EDIT: I dont want to show the image on the client, the purpose is to shrink the image and scale...
Im having some trouble resizing an image which is selected using a file input in a form before it must be uploaded to the server.
I have the following code monitoring my file input:
// monitor file inputs and trigger event
$(document).on('change', '.btn-file :file', function() {
var F = this.files;
if(!isImage( F[0] ))
{
alert(Not an image file);
}
var fileurl = resizeImage(F[0]);
console.log(fileurl);
var input = $(this),label = input.val().replace(/\/g, '/').replace(/.*//, '');
input.trigger('fileselect', [label]);
});
This function will call resizeImage which looks like this:
function resizeImage(file)
{
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var img = document.createElement(img);
img.src = window.URL.createObjectURL(file);
console.log(img.width);
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext(2d);
ctx.drawImage(img, 0, 0, width, height);
console.log(ctx);
var dataurl = canvas.toDataURL(image/png);
return dataurl;
}
Problem is, that my console log tells me that the return value from my resize function is data:,. I then started to console.log my way out of it, to narrow down where the problem is hiding. In my resizeImage function i logged the WIDTH of my img element which gave me a width of 0 which should not be correct ? .. I can't figure out what i have done wrong..