I am struggling with an issue that I can't define. I've pieced together this JQuery for uploading an image. When generating the preview, I'm using FileReader to get the image dimensions in order to control the resizing of the preview. As far as I can tell, that is working fine when I do console.log ($preview); inside img.onload = function() {};. But If I do that outside the function, it is undefined. I need access to the variable in the following functions. I've been studying scope, and from what I understand if I don't declare the variable inside the function like var variable = x; it shouldn't be local. I've also searched and searched the internet and SO for a solution but nothing seems to fit.
Is this an asynchronous issue or is it an issue with scope even though $preview is defined initially outside these functions? Can I return it from inside the function like in PHP?
var $preview;
if (previewsOn) {
if (isImgFile(ui.file)) {
var reader = new FileReader;
reader.onload = function() {
var img = new Image;
img.onload = function() {
if (img.width > 120 || img.height > 100) {
var maxWidth = 120;
var maxHeight = 100;
var ratio = 0;
var width = img.width;
var height = img.height;
if (width > maxWidth){
ratio = maxWidth / width;
$preview = $('<img/>').css("width", maxWidth);
$preview = $('<img/>').css("height", height * ratio);
height = height * ratio;
width = width * ratio;
}
if (height > maxHeight){
ratio = maxHeight / height;
$preview = $('<img/>').css("height", maxHeight);
$preview = $('<img/>').css("width", width * ratio);
width = width * ratio;
height = height * ratio;
}
} else {
$preview = $('<img/>');
}
};
img.src = reader.result;
};
reader.readAsDataURL(ui.file);
ui.readAs('DataURL', function(e) {
$preview.attr('src', e.target.result);
});
} else {
$preview = $('<i/>');
ui.readAs('Text', function(e) {
$preview.text(e.target.result.substr(0, 15) + '...');
});
}
} else {
$preview = $('<i>no preview</i>');
}
$($previewImg).empty(); $($preview).appendTo($previewImg);
$('<td/>').text(Math.round(ui.file.size / 1024) + ' KB').appendTo($row);
$('<td/>').append($pbWrapper).appendTo($row);
$('<td/>').append($cancelBtn).appendTo($row);
return $progressBar;
};
You assign value to $preview in .onload handler, but it is called some time later. According to your code following change could help:
var $preview;
if (previewsOn) {
if (isImgFile(ui.file)) {
$preview = $("<img/>");
(added initialization code after if statement)
Then replace lines like
$preview = $('<img/>').css("width", maxWidth);
with
$preview.css("width", maxWidth);
And remove
} else {
$preview = $('<img/>');
So variable will not be re-assigned.
answer to comment
Failure scenario timeline:
you code registers onload handler
you code continues execution, trying to do smth with $preview, which has no value yet
image finally loaded and onload handler triggered, assigning value to $preview
Related
I nearly have the theory down but am getting stuck wit the fine details. An image sizing function, given a var $data (which is the event object of a file input after changing) will return a var dataurl back (which is a dataurl jpeg).
My issue was getting dataurl to recognise it was updated inside a nested function. The code, as I show it below, was logging data:image/jpg;base64 to the console, showing dataurl was not updated.
Research led me to find that this is due to the asynchronous calls and this makes sense. The var wasn't changed in time before moving on and printing to the console. I've also learned that this is a standard situation to issue a callback to update the var.
Having made a few attempts at doing so, I can't find a clean (or working) method to update the var using a callback. I'll expand on this after I show my current code:
function clProcessImages($data) {
var filesToUpload = $data.target.files;
var file = filesToUpload[0];
var canvas = document.createElement('canvas');
var dataurl = 'data:image/jpg;base64';
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e, callback) {
img.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
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);
dataurl = canvas.toDataURL("image/jpeg",0.8);
callback(dataurl);
}
img.src = e.target.result
}
reader.readAsDataURL(file);
console.log(dataurl); // console log mentioned in question
return dataurl;
};
This is the code as it stands, somewhere in the middle of figuring out how to pull off the callback. I'm aware that in its shown state the callback isn't called.
My first hurdle was that I (seemingly) couldn't later call the reader.onload function again, as it appears to be an event specifically to be fired when the object is loaded, not something to call on manually at any time. My best guess was to create a new function that reader.onload would trigger, would contain all of the the current reader.onload function and I could specify directly later, to issue the callback, skipping referring to the onload event.
Seemed like a sound theory, but then I got stuck with the event object that the onload function passes through. Suppose I apply the above theory and the onload event calls the new function readerOnLoad(e). It would pass through the event object fine. However, when wanting to perform a callback later, how could I manually call readerOnLoad(e) as I don't see a way to pass on the event object from the same FileReader in an elegant way. It feels a little like I'm straying into very messy code* to solve whereas it feels like there should be something a little bit more elegant for a situation that doesn't feel too niche.
*The original $data event object variable was obtained by storing a global variable when a file input detected a change. In theory, I could create a global variable to store the event object for the FileReader onload. It just feels quite convoluted, in that the difference between my original code and a code that functions this way is quite severe and inelegant when the only difference is updating a var that wasn't ready in time.
When working with asynchronous function, you would usually want to pass a function as callback. You can use NodeJS style callback like this:
// asyncTask is an asynchronous function that takes 3 arguments, the last one being a callback
asyncTask(arg1, arg2, function(err, result) {
if (err) return handleError(err);
handleResult(result);
})
So in your case, you can do:
clProcessImages($data, function(dataurl) {
console.log(dataurl);
// Do you other thing here
});
function clProcessImages($data, onProcessedCallback) {
var filesToUpload = $data.target.files;
var file = filesToUpload[0];
var canvas = document.createElement('canvas');
var dataurl = 'data:image/jpg;base64';
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {
img.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
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);
dataurl = canvas.toDataURL("image/jpeg",0.8);
onProcessedCallback(dataurl);
}
img.src = e.target.result
}
reader.readAsDataURL(file);
return dataurl;
};
You might also want to pass error object to the callback like the first example, and handle it appropriately.
In short, always add a callback function as an argument to your own asynchronous function.
I'm using this plugin to create image zoom and gallery, yet I want to scale all images to fit with the container (using ratio algorithm).
Here is ratio function :
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
And this is how the gallery load images :
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
What I've tried :
var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
But scaleSize is not working properly since the current width and height is not yet defined (image not yet exist in dom).
Thanks for any pointers.
I took a look into plugin code and think you call your scaleSize() too early. An image with class simpleLens-big-image exists first after var img is set up and addClass() is done.
Try following:
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Try something like this and call the onload method. This will make sure that the image is loaded to the DOM before you resize
var img = $('<img>');
img.src = src ;
img.onload = function() {
// Run onload code.
} ;
I'm creating an image zoom via the scroll wheel but am having trouble passing variables between functions.
Before I call the img_scroll() function I need to get the minimum and maximum dimensions of the image I want to zoom in and out of. to get the dimensions I need to wait for the image to load first.
So right now I wait for the image to load, call the dimensions function, then once the dimensions are loaded, I call the scroll functions. But right now I'm having trouble passing the variables down the chain to the scroll function.
zoom = 0.01;
$(document).ready(function(){
$("#img_wrapper").imagesLoaded(function(){
getImgSizes();
});
});
function getMinImgSize() {
if ($("#img_wrapper img").width() <= $("#img_wrapper img").height()) {
$("#img_wrapper img").css("width", "100%");
} else {
$("#img_wrapper img").css("height", "100%");
}
min_width = $("#img_wrapper img").width();
min_height = $("#img_wrapper img").height();
return {height: min_height, width: min_width};
}
function getImgSizes() {
var newImg = new Image();
var width, height;
imgSrc = $("#img_wrapper img")[0].src;
minDimensions = getMinImgSize();
newImg.onload = function(minDimensions) { //incorect way to pass varaible to anonymous function
originalHeight = newImg.height;
originalWidth = newImg.width;
maxDimensions = {height: originalHeight, width: originalWidth};
img_scroll(minDimensions, maxDimensions);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
function img_scroll(minDimensions, maxDimensions){
var minDimensions = minDimensions;
var maxDimensions = maxDimensions;
$('#img_wrapper').mousewheel(function(event, delta, deltaX, deltaY) {
console.log(delta, deltaX, deltaY);
if (deltaY < 0) {
if ($("#img_wrapper img").width < maxDimensions.width) {
$("#img_wrapper img").width($("#img_wrapper img").width()*(1+zoom));
$("#img_wrapper img").height($("#img_wrapper img").height()*(1+zoom));
} else {
$("#img_wrapper img").width(maxDimensions.width);
$("#img_wrapper img").height(maxDimensions.height);
}
} else {
if ($("#img_wrapper img").width > minDimensions.width) {
$("#img_wrapper img").width($("#img_wrapper img").width()*(1-zoom));
$("#img_wrapper img").height($("#img_wrapper img").height()*(1-zoom));
} else {
$("#img_wrapper img").width(minDimensions.width);
$("#img_wrapper img").height(minDimensions.height);
}
}
});
}
Any help on how to pass the min & max dimension variables down the chain would be great.
Through the way closures work in Javascript, minDimensions is available to your anonymous function without being explicitly passed in. This should work:
function getImgSizes() {
var newImg = new Image();
var width, height;
var imgSrc = $("#img_wrapper img")[0].src;
var minDimensions = getMinImgSize();
newImg.onload = function() {
var originalHeight = newImg.height;
var originalWidth = newImg.width;
var maxDimensions = {height: originalHeight, width: originalWidth};
img_scroll(minDimensions, maxDimensions);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
EDIT: Use var to prevent global variables.
I have JS which resize the width and height of Image which is working fine if I used Alert before assigning the actual image src to the image object and if I omit the alertbox, it is not working. Please suggest me how to fix it.
`
<html>
<head>
<script type="text/javascript" language="javascript">
function resize_image_height_weight(id, hgt, wdth)
{
//alert(id);
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
// alert("Height=>" + heights + " Width=> " + widths);
if(heights > hgt || widths > wdth)
{
if(heights > widths)
{
var temp = heights/hgt;
var new_width = widths / temp;
new_width = parseInt(new_width);
heights = hgt;
widths = new_width;
}
else
{
var temp = widths/wdth;
var new_height = heights / temp;
new_height = parseInt(new_height);
heights = new_height;
widths = wdth;
}
}
Obj.height = heights;
Obj.width = widths;
}
</script>
</head>
<body>
<div>
<center>
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" id="i" alt="Google logo" height="150" width="150">
<script type="text/javascript">
document.images[document.images.length-1].onload = resize_image_height_weight("i",150,150);
</script>
</center>
</div>
</body>
</html>`
When you set the .src on an image, you have to wait until the image is successfully loaded until you can read it's height and width. There is an onload event handler that will tell you when the image is loaded.
Here's a place in your code where this issue could occur:
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
In this case, since the image was already elsewhere in the document, you should just read the height and width off the existing element rather than the new element.
Be very careful when testing because if the image is in your browser cache, it may load immediately, but when it's not in your cache, it takes some time to load and won't be available immediately.
Putting an alert at the right place in your script can allow the image to load before the script proceeds which could explain why it works with the alert.
As RobG mentions, your onload handler is also faulty (needs to be a function, not the returned result of a function).
Here's a simpler function to scale an image to fit the bounds. This uses a trick that you only need to set one size (height or width on the image) and the other will be scaled by the browser to preserve the aspect ratio.
function resizeImage(id, maxHeight, maxWidth) {
// assumes the image is already loaded
// assume no height and width is being forced on it yet
var img = document.getElementById(id);
var height = img.height || 0;
var width = img.width || 0;
if (height > maxHeight || width > maxWidth) {
var aspect = height / width;
var maxAspect = maxHeight / maxWidth;
if (aspect > maxAspect) {
img.style.height = maxHeight + "px";
} else {
img.style.width = maxWidth + "px";
}
}
}
You can see it in action here: http://jsfiddle.net/jfriend00/BeJg4/.
In the function assigned to onload:
> document.images[document.images.length-1].onload =
> resize_image_height_weight("i",150,150);
you are assigning the result of calling resize_image_height_weight which throws an error in IE. Set it to a function instead:
document.images[document.images.length-1].onload = function() {
resize_image_height_weight("i",150,150);
};
I have a image resizer function that resize images proportional. On every image load a call this function with image and resize if its width or height is bigger than my max width and max height. I can get img.width and img.height in FF Chrome Opera Safari but IE fails. How can i handle this?
Let me explain with a piece of code.
<img src="images/img01.png" onload="window.onImageLoad(this, 120, 120)" />
function onImageLoad(img, maxWidth, maxHeight) {
var width = img.width; // Problem is in here
var height = img.height // Problem is in here
}
In my highligted lines img.width don't work on IE series.
Any suggestion?
Thanks.
Don't use width and height. Use naturalWidth and naturalHeight instead. These provide the image unscaled pixel dimensions from the image file and will work across browsers.
Man, I was looking for this for 2 days. Thanks.
I'm using jQuery, but it doesnt matter. Problem is related to javascript in IE.
My previous code:
var parentItem = $('<div/>')
.hide(); // sets display to 'none'
var childImage = $('<img/>')
.attr("src", src)
.appendTo(parentItem) // sets parent to image
.load(function(){
alert(this.width); // at this point image is not displayed, because parents display parameter is set to 'none' - IE gives you value '0'
});
This is working in FF, Opera and Safari but no IE. I was getting '0' in IE.
Workaround for me:
var parentItem = $('<div/>')
.hide();
var childImage = $('<img/>')
.attr("src", src)
.load(function(){
alert(this.width); // at this point image css display is NOT 'none' - IE gives you correct value
childImage.appendTo(parentItem); // sets parent to image
});
This is how I solved it (because it's the only js on the site I didn't want to use a library).
var imageElement = document.createElement('img');
imageElement.src = el.href; // taken from a link cuz I want it to work even with no script
imageElement.style.display = 'none';
var imageLoader = new Image();
imageLoader.src = el.href;
imageLoader.onload = function() {
loaderElement.parentElement.removeChild(loaderElement);
imageElement.style.position = 'absolute';
imageElement.style.top = '50%';
imageElement.style.left = '50%';
// here using the imageLoaders size instead of the imageElement..
imageElement.style.marginTop = '-' + (parseInt(imageLoader.height) / 2) + 'px';
imageElement.style.marginLeft = '-' + (parseInt(imageLoader.width) / 2) + 'px';
imageElement.style.display = 'block';
}
It's because IE can't calculate width and height of display: none images. Use visibility: hidden instead.
Try
function onImageLoad(img, maxWidth, maxHeight) {
var width = img.width; // Problem is in here
var height = img.height // Problem is in here
if (height==0 && img.complete){
setTimeOut(function(){onImageLoad(img, maxWidth, maxHeight);},50);
}
}
var screenW = screen.width;
var screenH = screen.height;
//alert( screenW );
function checkFotoWidth( img, maxw )
{
if( maxw==undefined)
maxw = 200;
var imgW = GetImageWidth(img.src);
var imgH = GetImageHeight(img.src);
//alert(GetImageWidth(img.src).toString()); // img.width); // objToString(img));
if (imgW > maxw || (img.style.cursor == "hand" && imgW == maxw))
{
if (imgW > screenW) winW = screenW;
else winW = imgW;
if (imgH > screenH) winH = screenH;
else winH = imgH;
img.width=maxw;
img.style.cursor = "pointer";
img.WinW = winW;
img.WinH = winH;
//alert("winW : " + img.WinW);
img.onclick = function() { openCenteredWindow("Dialogs/ZoomWin.aspx?img=" + this.src, this.WinW, this.WinH, '', 'resizable=1'); }
img.alt = "Klik voor een uitvergroting :: click to enlarge :: klicken Sie um das Bild zu vergrössern";
//alert("adding onclick);
}
}
function GetImageWidth(imgSrc)
{
var img = new Image();
img.src = imgSrc;
return img.width;
}
function GetImageHeight(imgSrc)
{
var img = new Image();
img.src = imgSrc;
return img.height;
}
I'd try this:
function onImageLoad(img, maxWidth, maxHeight) {
var width, height;
if ('currentStyle' in img) {
width = img.currentStyle.width;
height = img.currentStyle.height;
}
else {
width = img.width;
height = img.height;
}
// whatever
}
edit — and apparently if I were to try that I'd learn it doesn't work :-) OK, well "width" and "height" definitely seem to be attributes of <img> elements as far as IE is concerned. Maybe the problem is that the "load" event is firing for the element at the wrong time. To check whether that's the case, I would then try this:
function onImageLoad(img, maxWidth, maxHeight) {
var width, height;
var i = new Image();
i.onload = function() {
width = i.width; height = i.height;
// ... stuff you want to do ...
};
i.src = img.href;
}
getDisplay().getImage().setUrl(imgURL);
final Image img = new Image(imgURL);
int w=img.getWidth();
int h=img.getHeight();