Javascript- how to get image width, height from the base64 code [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 26 days ago.
Improve this question
I have a base64 img encoded. How can I get the height and the width of it?
I tried this code but it doesn't work
var i = new Image();
i.onload = function(){
alert( i.width+", "+i.height );
};
i.src = imageData;

Your code works...
const imageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0BAMAAAA5+MK5AAAAG1BMVEXMzMyWlpacnJyqqqrFxcWxsbGjo6O3t7e+vr6He3KoAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFfklEQVR4nO3azW/bNhjAYUqWP46m0yY9Wm3a5hh3K7Cj3KQ9x96Qsz1kSI9OBgQ7xu0O/bPHl6Rirk0iy6krZvs9QCwq8gvwBcUPUVYKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAt7jKXy3Kcvf3wfmPjG7WO6314NqVs9ycHPy46B8u1c6enPRs8Zm7srQn11uMblgSVn7syoWUM1d+ssXoho3Dys9deSbljivvbjG6YWHlu1o/Ld77e/ZC69+yScU9+7Dohi31c0tGpI6t6tK11Vxy6PlG3E50wy5c37TG+qn5bNvuajrriTmZ3N9dHxbdsIkOy0M55FLtth5IObX5bCm6YaNgJJrbpjI5zOT2tbVu3z9SPSy6YfOdVdlPTGPdl2nL3qvmzt1edMPy1S3Zc3epuU2fyXA1dNdvBunUj9eTctVSKzpCbkq2utq1YUv+d6EP7clIl6tyP15n4bC9fnR8sqAJ235QsseJ67k3R+UnLJPaalSvEx2dnn7SezP4o5Byy7ehbb+yvcr2U+WUPdY7G0VHp6v7I7Mas9l0fBv2JMW576XL1e1t2nshWT3ZKDo6bf3KrkT3lQxQLqlMBqzc39ZjP2DZ/5uyX6zUj45Oyy/CB8UalZ+Ye7rjB/L60bHxT1ha+m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mMC9XNDyQBOaxGeNUd+i+GqbtOcaTLeV09vtTX0Fk0XYPGXDZdgcYkB03XAACAhv0DZOEQfKmW0XEAAAAASUVORK5CYII=";
var i = new Image();
i.onload = function() {
alert(i.width + ", " + i.height);
};
i.src = imageData;

var img = document.createElement('img');
img.addEventListener('load', function() {
document.write(img.width + ' × ' + img.height);
});
img.src = "<your base64 string>";

Related

Canvas ctx.drawimage() not working [duplicate]

This question already has an answer here:
Canvas: drawImage not drawing image to canvas
(1 answer)
Closed 8 years ago.
I am trying to render some pictures into a canvas, but when I use my rendering function, the images won't appear. The function is:
function populateSquareImages(){
for(var i = 0,ii = squares.length; i < ii; i++) {
if(squares[i].hasImage) {
var img = new Image();
img.src = "../Content/Squares/images/square_" + squares[i].uniqueId + ".png";
context.drawImage(img, squares[i].x, squares[i].y);
}
}
}
After some debugging, I am sure that x and y are accurate. The image file path is correct as well. Any idea of what might be wrong here?
You need to wait for the image to load before attempting to draw it. This should work:
function populateSquareImages () {
for (var i = 0, ii = squares.length; i < ii; i++) {
if (squares[i].hasImage) {
var img = new Image(),
square = squares[i];
img.src = "../Content/Squares/images/square_" + squares[i].uniqueId + ".png";
img.onload = function () {
context.drawImage(img, square.x, square.y);
};
}
}
}
The variable i will not be correct inside the callback function by the time it gets called, so store the value of squares[i] in another variable called square.

Storing random array value with intervals [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How would I go about replacing the old 'box' with a white/no background?
var counter = 11;
var check = 0;
var boxes = ["box_1","box_2","box_3","box_4"];
clock = setInterval(function() {
counter--;
if(counter==0) {
clearInterval(clock);
document.getElementById("counter").innerHTML="Time Left: 0 seconds.";
} else {
var box = boxes[Math.floor(Math.random()*boxes.length)];
document.getElementById("counter").innerHTML="Time Left: " + counter.toString() + " seconds.";
document.getElementById(box).style.backgroundColor="#000";
}
}, 1000);
I attempted to store the box as old_box -> old_box = box which didn't work.
It seems people are misunderstanding.
I want to store the box value so I can call it back on the next loop and set it to white, while the new box can be set to black.
You need to remember the box:
var counter = 11;
var check = 0;
var boxes = ["box_1","box_2","box_3","box_4"];
var lastbox = false;
clock = setInterval(function() {
counter--;
if(counter==0) {
clearInterval(clock);
document.getElementById("counter").innerHTML="Time Left: 0 seconds.";
} else {
if (lastbox) {
document.getElementById(lastbox).style.backgroundColor = "#FFF";
}
lastbox = boxes[Math.floor(Math.random()*boxes.length)];
document.getElementById("counter").innerHTML="Time Left: " + counter.toString() + " seconds.";
document.getElementById(lastbox).style.backgroundColor="#000";
}
}, 1000);
jsBin DEMO
Simply set the background to #000 to the element
which index-matches the random number (r==i)
function $id(_) { return document.getElementById(_); }
function $el(_) { return document.querySelectorAll(_); }
function game() {
if (!c) clearInterval( clock );
$cou.innerHTML = "Time Left: "+ (c--) +" seconds.";
var r = ~~(Math.random()*n);
for(var i=0; i<n; i++) $box[i].style.backgroundColor = i==r?"#000":"#fff";
}
var $box = $el("[id^=box_]"),
$cou = $id("counter"),
n = $box.length,
c = 10,
clock = setInterval(game, 1000);
As you can see I've also used some nice reusable functions so further in your project you don't need to loose your fingers writing all over the place document.getElementById but simply:
$id("elementID")
or if you want to get more elements using a wide spectrum of selectors: (slower)
$el(".elements") // [] array collection
$el("[id^=prefix]") // [] array collection
$el("input") // [] array collection

Javascript: How to get width of image URL

I'm trying to get the width of an image after a change in the height and I only have the URL (the image is not in a tag in the HTML) so I tried this code:
var img = document.createElement("img");
img.src = "./images/niceImages.jpg";
img.style.height = "200px";
console.log(img.clientWidth);
But the property "clientWidth" returned 0. I know that maybe with JQuery it is a lot easier however, I want do it with pure Javascript.
Does anyone know if this can be done? Or at least how to get the aspect ratio or width and height of the image URL?
If you append the image you create to the DOM then you should find that the width is then calculated and is then available as normal
var img = document.createElement("img");
img.src = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png";
img.onload = function(){
img.style.height = "200px";
img.style.visibility = 'hidden';
document.body.appendChild(img);
console.log(img.clientWidth);
}
I figured out some better solutions -
Javascript
function loadImage() {
const imgSrc = 'https://cdn.pixabay.com/photo/2015/03/26/09/47/sky-690293_1280.jpg'
const img = new Image();
img.src = imgSrc;
img.onload = function() {
document.body.appendChild(img); // You can get the image ratio without inserting the image in body
alert('Image ratio' + img.width/img.height);
}
}
<button onClick="loadImage()">Load Image</button>
Angular (Typescript) - ( Snippet will not run because of angular unavailability )
public getImageRatio(url: string): Promise <any> {
return Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = function() {
resolve(img.width / img.height);
};
img.onerror = function() {
reject('Image failed to load');
};
});
}
async loadImage(url) {
const imageRatio = await getImageRatio('image-url-here');
alert(imageRatio);
}
loadImage(url);

Upload the same image file twice - Javascript

I have an image uploader in my drawing application that I've written in Javascript. I want to allow the user to place multiple of the same image on the canvas. However, when I try to upload an image that's already on the canvas, nothing happens and a breakpoint in my event handler for the uploader never gets hit. What's going on and how can I fix it? Thanks!
Here's the code for my image handler:
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
img.className = 'drag';
img.style.left = 0;
img.style.top = 0;
context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
images.push(img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
};
I do tend to agree with Rene Pot to use the same image again (duplicate button), but you still can't prevent the user from inserting/loading the same image again. I've encountered the problem a while ago and used this bit of code to check if the image is already cached (if cached, there is no load, hence the onload won't fire either).
var img = new Image();
img.src = event.target.result;
var insertImage = function() {
img.className = 'drag';
img.style.left = 0;
img.style.top = 0;
context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
images.push(img);
}
if(img.complete){
img.onload = insertImage;
} else {
insertImage();
}
Hope that helps.

jQuery/javascript - Get Image size before load

I have a list of images that is rendered as thumbnails after upload. The issue that I have is I need the dimensions of the fully uploaded images, so that I can run a resize function if sized incorrectly.
Function that builds the image list
function buildEditList(json, galleryID)
{
//Hide the list
$sortable = $('#sortable');
$sortable.hide();
for(i = 0, j = json.revision_images.length; i < j; i++) {
$sortable.append(
"<li id='image_" + json.revision_images[i].id + "'><a class=\"ui-lightbox\" href=\"../data/gallery/"
+ galleryID
+ "/images/album/"
+ json.revision_images[i].OrgImageName
+ "\"><img id=\""
+ json.revision_images[i].id
+ "\" alt=\"\" src=\"../data/gallery/"
+ galleryID
+ "/images/album/"
+ json.revision_images[i].OrgImageName
+ "\"/></a></li>"
).hide();
}
//Set first and last li to 50% so that it fits the format
$('#sortable li img').first().css('width','50%');
$('#sortable li img').last().css('width', '50%');
//Fade images back in
$sortable.fadeIn("fast",function(){
var img = $("#703504"); // Get my img elem -- hard coded at the moment
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
alert(pic_real_height);
});
}
I have been trying to use the solution from this stackoverflow post, but have yet to get it to work, or it may just be my code. if you have any ideas on this I could use the help. Currently the alert is coming back undefined.
There's a newer js method called naturalHeight or naturalWidth that will return the information you're looking for. Unfortunately it wont work in older IE versions. Here's a function I created a few months back that may work for you. I added a bit of your code below it for an example:
function getNatural($mainImage) {
var mainImage = $mainImage[0],
d = {};
if (mainImage.naturalWidth === undefined) {
var i = new Image();
i.src = mainImage.src;
d.oWidth = i.width;
d.oHeight = i.height;
} else {
d.oWidth = mainImage.naturalWidth;
d.oHeight = mainImage.naturalHeight;
}
return d;
}
var img = $("#703504");
var naturalDimension = getNatural(img);
alert(naturalDimension.oWidth, naturalDimension.oHeight)​

Categories

Resources