I need to resize multiple images.
This is the HTML:
<img id="thumbnailId" src='http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
<img id="thumbnailId" src='http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
And my JavaScript code:
$(document).ready(function() {
console.log("ready to go");
var imgs = getElementsById("thumbnailId");
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
img.onload = function () {
console.log("image is loaded");
}
resizeImage(img);
}
});
The functions called from this:
function getElementsById(elementID) {
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++) {
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
And
function resizeImage(img) {
console.log("width, height, src " + img.width + ", " + img.height + ", " + img.src);
console.log("loaded? " + img.complete);
var width = img.width;
var height = img.height;
var constant = 100;
var ratio = width / height;
console.log("ratio " + ratio);
if(width > constant || height > constant) {
var newWidth = constant;
var newHeight = constant*ratio;
if(width > height) {
newWidth = constant;
newHeight = constant*ratio;
} else {
newWidth = constant*ratio;
newHeight = constant;
}
console.log("newWidth, newHeight " + newWidth + ", " + newHeight);
//img.width = newWidth;
//img.height = newHeight;
img.style.width = newWidth + "px;";
img.style.height = newHeight + + "px;";
console.log("img from url AFTER " + img.width + ", " + img.height);
}
console.log("==========================");
}
The code seems right, and works for one image. But not for multiple images. The output I get is this:
ready to go
resizeImages called
width, height, src 84, 110, http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg
loaded? true
ratio 0.7636363636363637
newWidth, newHeight 76.36363636363637, 100
img from url AFTER 84, 110
==========================
width, height, src 86, 110, http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg
loaded? true
ratio 0.7818181818181819
newWidth, newHeight 78.18181818181819, 100
img from url AFTER 86, 110
==========================
2 image is loaded
So basically I'm not even getting the correct dimensions of the image at the start. For some reason the width is always 110. Any idea what's going on here?
HTML element ID must be unique.
You cannot have more than one element using the same ID
Use HTML element Class instead of ID. Use document.getElementsByClassName to filter these elements.
First of all in html id can not be duplicate in whole html page .. and second thing ... you did not called image resize function because it is function's .. out of scope
$(document).ready(function() {
console.log("ready to go");
var imgs = getElementsById("thumbnailId");
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
img.onload = function () {
console.log("image is loaded");
//call should be here
resizeImage(img);
}
//resizeImage(img);
}
});
Related
I am looking for a way to resize individually several div on a page (like a browser window, that you can resize from a bottom corner), keeping the same proportions/ratio. I made the code work for a class .handle and .dragger, but all the div with the same class are being modified at the same time, while I would like it to be executed only for the div we click on.
Here is the code to resize that I'm working with:
$(".handle").bind('mousedown', draggerDown);
$("body").bind('mouseup', draggerUp);
function calculateNewSize(size) {
// {currHeight, currWidth, newHeight, newWidth, offsetX, offsetY}
var newWidth;
var newHeight;
if (Math.abs(size.offsetX) > Math.abs(size.offsetY)) {
newWidth = size.currWidth + size.offsetX;
newHeight = newWidth * (size.currHeight / size.currWidth);
} else {
newHeight = size.currHeight + size.offsetY;
newWidth = newHeight * (size.currWidth / size.currHeight);
}
return {
"height": newHeight,
"width": newWidth
};
}
function draggerDown() {
event.stopPropagation();
event.preventDefault();
currentX = event.pageX;
currentY = event.pageY;
currentHeight = $(".dragger").height();
currentWidth = $(".dragger").width();
$("body").bind('mousemove', draggerMove);
}
function draggerMove() {
var draggerElements = document.getElementsByClassName("dragger");
for (var n = 0; n < draggerElements.length; ++n) {
var targetStyle = window.getComputedStyle(draggerElements[n], null);
var newHeight = currentHeight + (event.pageY - currentY);
var newWidth = currentWidth + (event.pageX - currentX);
// AT THIS POINT, THE LOGIC COMES IN.
// CUSTOMIZE 'calculateNewSize' function above
var newSize = calculateNewSize({
"currHeight": currentHeight,
"currWidth": currentWidth,
"newHeight": newHeight,
"newWidth": newWidth,
"offsetX": (event.pageX - currentX),
"offsetY": (event.pageY - currentY)
});
currentHeight = newSize.height;
currentWidth = newSize.width;
newHeight = newSize.height;
newWidth = newSize.width;
// AT THIS POINT, THE LOGIC IS DONE.
// SIZES SHOULD BE COOL NOW
$(".dragger").css("height", newHeight + "px");
$(".dragger").css("width", newWidth + "px");
console.log($(".dragger").height());
currentX = event.pageX;
currentY = event.pageY;
}
}
function draggerUp() {
$("body").unbind('mousemove');
}
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "xUAZ5"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
}
I am trying to do it with that methodology (from another project) but I don't really know if it could work with the previous code:
var u;
for(var i=1; i<13; i++) {
var specificClass= document.getElementsByClassName("class"+i);
for (u = 0; u < specificClass.length; u++) {
specificClass[u].addEventListener("click", thefunction);
}
}
function thefunction(evenement) {
// alert(evenement.target.classList)
var clickedElement = document.getElementsByClassName(evenement.target.classList);
for (u = 0; u < clickedElement.length; u++) {
clickedElement[u].style etc.
}
}
In that case I would these two groups of class: handle1, handle2, handle3,... and dragger1, dragger2, dragger3...
Here is my simplified html body:
<div class="draggableDiv dragger div1">
<div class="handle"></div>
</div>
<div class="draggableDiv dragger div2">
<div class="handle"></div>
</div>
Any other methodology is very welcomed of course, this is only what I've been trying :)
Let me know if you would need more details
Thanks!
I am trying to re-size an image in a popup. The original image is 6000 x 4000. I do a check to see if the image is greater than 500, and if so I just try and set the image to 500. Trying to set it using 'this', makes the pop open in a tab and the image is still its original size. If I try and set the image not using 'this', the pop up works as intended regarding where it is positioned on screen and the size of the box, but the image, is still its original size--6000 x 4000. (PS: I have to use ES5 as well.)
What gives?
Thanks,
CM
<script language="javascript" type="text/javascript"><!--
// let i=0;
function resize() {
console.log("Testing");
let i=0;
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1 && window.navigator.userAgent.indexOf('SV1') != -1) {
i=30; //This browser is Internet Explorer 6.x on Windows XP SP2
} else if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
i=0; //This browser is Internet Explorer 6.x
} else if (window.navigator.userAgent.indexOf('Firefox') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=25; //This browser is Firefox on Windows
} else if (window.navigator.userAgent.indexOf('Mozilla') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=45; //This browser is Mozilla on Windows
} else {
i=80; //This is all other browsers including Mozilla on Linux
}
var imgWidth = document.images[0].width;
var imgHeight = document.images[0].height;
console.log("Original image width is: " + imgWidth);
console.log("Original image height is: " + imgHeight);
if(imgWidth > 500){
//Shrink the image to size of popup frame
this.imgWidth = 500;
this.imgHeight = 500;
console.log("Adjusted image width is: " + imgWidth);
console.log("Adjusted image height is: " + imgHeight);
//Get display/screen width and height
var screenWidth = screen.width;
var screenHeight = screen.height;
console.log("Screen width is: " + screenWidth);
console.log("Screen height is: " + screenHeight);
//Set popup position on display/screen
var leftpos = screenWidth / 2 ;
var toppos = screenHeight / 2 - imgHeight / 2;
console.log("Left position is: " + leftpos);
console.log("Top position is: " + toppos);
//Set popup frame width and height equal to adjusted image width and height
var frameWidth = imgWidth;
var frameHeight = imgHeight+i;
console.log("Frame width is: " + frameWidth);
console.log("Frame height is: " + frameHeight);
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth,frameHeight+i);
}
else if (document.documentElement && document.documentElement.clientWidth) {
var imgHeight = document.images[0].height + 40 - i;
var imgWidth = document.images[0].width + 20;
var height = screen.height;
var width = screen.width;
var leftpos = width / 2 - imgWidth / 2;
var toppos = height / 2 - imgHeight / 2;
frameWidth = imgWidth;
frameHeight = imgHeight + i;
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth, frameHeight + i);
} else if (document.body) {
window.resizeTo(document.body.clientWidth, document.body.clientHeight - i);
}
self.focus();
}//end resize() function
//--></script>
Use
var imgWidth = document.images[0].style.width;
instead of
var imgWidth = document.images[0].width;
PROBLEM: I have 2 images, one is taken from my database using src=data:image;base64,$row[2] and has given dimensions.
The other image is taken from an HTML element with ID=img00 and it is a transparent image. I need the transparent image to have the same width and height of the image taken from my database.
MY GUESS: I would like to save getMeta output to 2 variables for width and height, that I would later use instead of '200px'.
Do you believe there's a smarter way than this code?
Else, what would I have to do to save getMeta output and use it instead of that 200px?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) { alert(width + 'px ' + height + 'px') }
);
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = '200px';
img00.style.width = '200px';
}
If you want to use the values from inside getMeta, you are going to have to change the timing of the execution of the last block of code. Perhaps something like this?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
function sizeImg00(w,h){
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = h + 'px';
img00.style.width = w + 'px';
}
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) {
console.log(width + 'px ' + height + 'px');
sizeImg00(width, height);
}
);
I have a function cropAndCenterImage() that i need to use for iterating every class named .photo-card-image-wrapper. I know how to do each() functions in jquery, but the input parameter of cropAndCenterImage() function needs to be name of the class as in cropAndCenterImage(".photo-card-image-wrapper"), every instance of it.
This is what I have so far:
$(function() {
$("div.photo-card-image-wrapper").each(function() {
cropAndCenterImage("every instance of photo-card-image-wrapper class");
});
});`
EDIT
function cropAndCenterImage(el, size) {
//el = img wrapper
//img = img element
if (size === undefined || size === null) {
var portfolio = document.getElementById("portfolio").offsetWidth;
console.log(portfolio);
if (portfolio < 1200) {
size = portfolio / 4;
} else if (portfolio < 960) {
size = portfolio / 3;
} else {
size = portfolio / 5;
}
}
var $el = $(el);
var $img = $(el + " img");
console.log($el);
console.log($img);
$img.width("auto").height("auto");
var imgWidth = $img.width();
var imgHeight = $img.height();
console.log(imgHeight, imgWidth);
//hopefully that returns the img to it's default height and width by making the inline style to empty quotes
if( imgWidth > imgHeight ) {
//Crop image
//console.log("width greater than height");
if ( imgHeight >= size ) {
console.log("hit if");
$img.height(size);
imgHeight = $img.height();
imgWidth = $img.width();
$el.height(imgHeight).width(imgHeight);
} else {
console.log("hit else");
$el.height(imgHeight).width(imgHeight);
$img.height(imgHeight).width(imgWidth);
}
//Center image horizontally
var leftInt = (imgWidth - $el.width()) / 2;
$img.css({ "margin-left": "-" + leftInt + "px", "margin-top": "0" });
} else {
//Crop image
console.log("height greater than width");
if ( imgWidth >= size ) {
$img.width(size);
imgHeight = $img.height();
imgWidth = $img.width();
$el.height(imgWidth).width(imgWidth);
} else {
$el.height(imgWidth).width(imgWidth);
$img.height(imgHeight).width(imgWidth);
}
imgHeight = $img.height();
//Center image vertically
var topInt = (imgHeight - $el.height()) / 2;
//console.log(topInt);
$img.css({ "margin-top": "-" + topInt + "px", "margin-left": "0"});
}
}
HTML
<div class="photo-card-image-wrapper"><img src="images/art1.jpg" class="art" /></div>
<div class="photo-card-image-wrapper"><img src="images/art2.jpg" class="art" /></div>
<div class="photo-card-image-wrapper"><img src="images/art3.jpg" class="art" /></div>
<div class="photo-card-image-wrapper"><img src="images/art4.jpg" class="art" /></div>
<div class="photo-card-image-wrapper"><img src="images/art5.jpg" class="art" /></div>
etc
$(function() {
$("div.photo-card-image-wrapper").each(function() {
cropAndCenterImage($(this));
});
});
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();