Reputation: 10350
Here is a js script to handle resizing jpeg image on client side. The resizing is handled when the image is loaded by an anonymous callback function defined in asynchronous
img.onload()
. The callback function checks the width and height of the loaded image and resize if it is too large. The problem with the code below is that the callback function is not invoked when the image is loaded with img.src = _URL.createObjectURL(f)
.
$('#uploaded_file_file_for_upload').change(function(){
var _URL = window.URL || window.webkitURL;
var img;
var max_width = 0;
var max_height = 0;
var max_size_mb;
var f = $(this)[0].files[0];
if (f != null) {
max_width = $('#max_width').val();
max_height = $('#max_height').val();
max_size_mb = $('#max_size_mb').val();
alert(max_width +', ' + max_height);
$('#file_name').val(f.name);
alert(f.name);
$('#file_size').val(f.size/1024);
$('#file_type').val(f.type); //image/jpeg
$('#file_extension').val(f.name.split('.').pop().toLowerCase());
alert(f.type);
alert(f.name.split('.').pop().toLowerCase());
if (f.type == 'image/jpeg') {
img = new Image();
img.onload(function (){
var w = this.width, h = this.height;
alert('hi-max' + max_width + ' -- ' + max_height);
alert('hi' + w + ' xx ' + h);
if (w > max_width || h > max_height) {
if (w > max_width){
h = Math.ceil(h * max_width / w);
w = max_width;
} else {
w = Math.ceil(w * max_height / h);
h = max_height;
};
alert('before resize, ' + w + ' ?? ' + h );
resize(this, w, h);
$('#remove').val('true');
};
});
img.src = _URL.createObjectURL(f);
};
};
Upvotes: 0
Views: 52
Reputation: 8666
You need to set a function to the onload
property, not call the function with your function as a property:
img.onload = function() {
// TODO
};
Upvotes: 2