I'm working on an app that is dynamically generating images with Javascript's image() object. Code below, where object is the URL I am passing in -
resizeImage: function(object) {
var img = new Image();
img.src = object;
console.log(img);
console.log(img.width);
console.log(img.height);
var ratio;
if(img.width > img.height) {
ratio = 82/img.width;
} else {
ratio = 82/img.height;
}
img.height *= ratio;
img.width *= ratio;
return img;
},
The output of my console log shows the image object is created with source set to URL -
<img src="https://z3nburmaglot.zendesk.com/attachments/token/F0Y7C9UfUcOaA7nCMJfE5T1yB/?name=Show+Support+Tickets+on+Customer+View.png"> and height and width of 0.
Some of the images load fine - they set height and widgth appropriately and if I refresh the JS (run the function again), the images that had 0 height and width suddenly change to the correct height and width.
Any thoughts on why constructing an image this way would fail sometimes?
Sounds like your image hasn't loaded yet when you get its width or height. Then it will be 0.
When you refresh, the image is in your browser cache and will load immediately so its width and height are available straight up.
Use the onload() event of the Image object to execute code once the image has been loaded properly
resizeImage: function(object) {
var img = new Image();
// first set onload event
img.onload = function() {
console.log(img);
console.log(img.width);
console.log(img.height);
var ratio;
if(img.width > img.height) {
ratio = 82/img.width;
} else {
ratio = 82/img.height;
}
img.height *= ratio;
img.width *= ratio;
}
// then set the src
img.src = object;
return img;
},
Related
I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page.
I want to set the height and width of an image in the JS file. Any good ways on doing this?
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>
Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length;
for(i=0;i<L;++i){
document.images[i].style.height = 'auto'; //setting CSS value
document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}
you can see the result here
In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:
<div>
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image"
width="10%" id="f" >
</div>
js file:
var b=0;
function fifo() {
if(b==0){
document.getElementById("f").width = "300";
b=1;
}
else
{
document.getElementById("f").width = "100";
b=0;
}
}
Direct manipulation
HTML tag declaration for image:
<img id="my-img" src="src/to/your/image.jpg" width="1280px" height="720px" />
<!-- OR -->
<img id="my-img" src="src/to/your/image.jpg" style="width: 1280px; height: 720px;" />
Handling html tag by direct access to object image:
const myImg = document.getElementById("my-img");
// Set a new width and height
myImg.style.width = "800px";
myImg.style.height = "450px";
// Or set a new width and height by attribute
// This option is not advisable because the attribute has a
// low priority over the style property.
myImg.setAttribute("width", 800);
myImg.setAttribute("height", 450);
Functions for manipulation
Using the updateImageSizeWithWidth or updateImageSizeWithHeight method below, you can increase or decrease any image without having to explicitly specify the exact width and height, you only need one value out of these two to update the image size.
/**
* Update image size using width
*
* param {HTMLImageElement} img
* param {number} newWidth
*/function updateImageSizeWithWidth(img, newWidth) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newHeight = (newWidth * oldHeight)/oldWidth;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
/**
* Update image size using height
*
* param {HTMLImageElement} img
* param {number} newHeight
*/
function updateImageSizeWithHeight(img, newHeight) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newWidth = (newHeight * oldWidth)/oldHeight;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
updateImageSizeWithWidth(myImg, 800);
// Or
updateImageSizeWithHeight(myImg, 450);
// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());
You can do this:
.html file:
<img src="src/to/your/img.jpg" id="yourImgId"/>
.js file:
document.getElementById("yourImgId").style.height = "heightpx";
The same you can do with the width.
I am trying to detect if an image was clicked. To give some context, I am making a cookie clicker game where if you click it 10 times, a new image will appear which will give double points. For the first image I used
document.querySelector('#clickme1').onclick=scooore;
Then I am adding new images with the following function:
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
My problem is how do I add to my variable (scree) since it is local and the first way needs to use a whole diff function.
function scooore() {
scree = scree + 1;
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times";
Been working for 40+ mins on this probably 1 line of code solution and couldn't find a solution so turning to the nice people at stack overflow
In addition to the code I posted below, what will really help you as you continue to develop your project is if you have an array of data for each image (whether that is an object or another array).
// Put on outside so that image may change instead of clone
var img = document.createElement("img")
// Fill out initial image specs
img.src = src
img.width = width
img.height = height
img.alt = alt
function show_image(src, width, height, alt) {
img.src = src
img.width = width
img.height = height
img.alt = alt
}
var scree = 0
function scooore() {
scree++
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times"
// If score is divisible by 10
if (scree % 10 === 0) {
show_image(src, width, height, alt)
}
}
document.querySelector('#clickme1').onclick = scrooore()
I am attempting to resize an image's dimensions, whilst retaining it's aspect ratio. This seems like a very simple task, but I cannot find a rellevent answer anywhere.. (relating to JavaScript's Image() object). I'm probably missing something very obvious. Below is what I am trying to achieve:
var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
if (img.width > 200){
img.width = 200;
img.height = (img.height*img.width)/img.width;
}
if (img.height > 200){
img.height = 200;
img.width = (img.width*img.height)/img.height;
}
};
This is to proportionally resize an image before being drawn onto a canvas like so: context.drawImage(img,0,0,canvas.width,canvas.height);.However it would appear I cannot directly change Image()dimensions, so how is it done? Thanks.
Edit: I haven't correctly solved the image proportions using cross-multiplication. #markE provides a neat method of obtaining the correct ratio. Below is my new (working) implementation:
var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);
Here's how to scale your image proportionally:
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
Usage:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png";
function start(){
canvas.width=100;
canvas.height=100;
var w=img.width;
var h=img.height;
// resize img to fit in the canvas
// You can alternately request img to fit into any specified width/height
var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height);
ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer);
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Original Balloon image resized to fit in 100x100 canvas</h4>
<canvas id="canvas" width=100 height=100></canvas>
The image dimensions are set in the constructor
new Image(width, height)
// for proportionally consistent resizing use new Image(width, "auto")
or
the context.drawImage()
the arguments are as follows:
context.drawImage(image source, x-coordinate of upper left portion of image,
y-coordinate of upper left portion of image,image width,image height);
simply position the the image with the first two numeric coordinates and then manually adjust the size with the last two (width,height)
//ex.
var x = 0;
var y = 0;
var img = new Image (200, "auto");
img.src = "xxx.png";
context.drawImage(img,x,y,img.width,img.height);
My web application has many image presentation features, and most of time we need to resize them. I attempted to get its real width and height values by the following fragment code:
var image = new Image();
image.src = IMAGE_URL;
var width = image.width;
var height = image.height;
The above code runs no problem on browsers like Firefox and IE 10, but it returns 0 on Chrome. I guess Chrome doesn't support this.
Can anybody gives me guidance on this?
you need to get width and height after the image loads and understands what its made of.
try:
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
}
image.src = IMAGE_URL;
hope that helps
Try this
img = new Image();
img.onload = function() {
width = this.width;
height = this.height;
};
Onload help you to get width and height.
You need to wait for the load event, otherwise the dimensions of the image won't be known.
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
// These values will now be correct.
};
image.src = IMAGE_URL;
I am trying to create an uploading image resizing function using javascript. However, using filereader to convert upload files into base64, gives no image on canvas. Rather, if I use an external image, and convert that into base64, the function works like a charm. How would that be? What is the problem?
Here is my code, it's pretty long.
//When changes are made to our input field
$ ('#input-file').change (function (evt) {
//The selected file is recovered
var file = evt.target.files [0];
//And processFiles function that will resize and send the file to the server is started
processFiles (file);
});
processFiles = function (file) {
var reader = new FileReader ();
//When the file has been completely read, the function will be executed ResizeImage
reader.onloadend = function (evt) {
//Reader.result represents our base64 encoded file
ResizeImage (reader.result, file);
};
//Allows you to play the file
reader.readAsDataURL (file);
};
ResizeImage = function (data, file) {
var fileType = file.type,
maxWidth = 960
maxHeight = 960;
//The file is loaded in a <img>
var image = new Image ();
image.src = data;
//Once the image is loaded, the following operations are performed
image.onload = function () {
//The ImageSize function calculates the final file size keeping the proportions
var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
ImageWidth = size.width,
imageHeight = size.height,
//We create a canvas element
//canvas = document.createElement ('canvas');
canvas=document.getElementById('hahaha')
canvas.width = ImageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext ("2d");
//DrawImage will allow resizing the image
//This is our image here
var img=document.getElementById('haha')
ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);
//Allows you to export the contents of the canvas element (our resized image) base64
data = canvas.toDataURL(fileType);
alert(data)
//All the elements used for resizing is suppressed
delete image;
delete canvas;
//SubmitFile (data);
}
};
//Function to resize an image keeping the proportions
ImageSize = function (width, height, maxWidth, maxHeight) {
var newWidth = width,
newHeight = height;
if (width> height) {
if (width> maxWidth) {
newHeight = maxWidth / width;
newWidth = maxWidth;
}
else {}
if (height> maxHeight) {
newWidth = maxHeight / height;
newHeight = maxHeight;
}
}
return {width: newWidth, height: newHeight};
};
You may refer this fiddle, http://jsfiddle.net/aliasm2k/tAum2/ for some ideas. It may help you. This is a fiddle I implemented just for fun to generate a thumbnail of a user selected image. It uses FileReader API to select the file and then loads the thumbnail on a canvas.
Personally I'd preffer classic JS than using jQuery and lot of event handlers are used
oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()