This question already has answers here:
Get image width and height from the Base64 code in JavaScript
(5 answers)
How to get the image size (height & width) using JavaScript
(33 answers)
Closed 8 years ago.
I have an image that is created via a FileReader:
var fileReader = new FileReader();
var deferred = $.Deferred();
fileReader.onload = function(event) {
deferred.resolve(event.target.result);
};
fileReader.onerror = function() {
deferred.reject(this);
};
fileReader.readAsDataURL(file);
return deferred.promise();
This returns a base64 encoded string which I use with:
var img = $('<img src="' + fileB64 + '">');
Then this is added to my page.
I wish to get the original height and width of that image.
I can get the size of it on the page via:
this.img = img;
this.imgWidth = this.img.width();
this.imgHeight = this.img.height();
But I wish to get its original width and height.
I think the only way you can determine the image's width and height is to actually create an image element and then get the dimensions from that:
var img = new Image();
img.src = fileB64;
var width = img.width;
var height = img.height;
I'm assuming (i.e. I haven't checked) that loading a data: URL into an image's src property will cause it to load synchronously. Use img.onload otherwise.
Having created the element off-screen like this, you can then add the very same element into the page.
Related
I'm uploading an image file (size 368KB) and reading it as a 64 bit data url. The size of the data url is 501999 bytes. When I now paint it on a canvas and try to find the size of the data url of the canvas, I'm getting a size of 1091506 bytes.
I can expect some increase after painting it on canvas, but an image blowing to twice its size is pretty weird. If I use an image of around 230KB, the image blows up to more than 8-9 times its original size. However, if I use an image of around 50KB, the increase in size is only marginal.
What's the reason?
Stackblitz is here
let uploadElement = document.getElementById('upload')
uploadElement.onchange = onImageChange;
function onImageChange(){
let inputFile = event.target.files[0];
let fileReader = new FileReader();
fileReader.onload = function(event){
let imageAsBase64 = event.target.result;
let initialSize = imageAsBase64.length;
console.log(initialSize);
const tempImage = new Image();// <HTMLImageElement>document.getElementById('test');
tempImage.src = imageAsBase64;
tempImage.onload = () => {
const element = document.createElement('canvas');
element.width = tempImage.width;
element.height = tempImage.height;
const ctx = element.getContext('2d');
ctx.drawImage(tempImage, 0, 0, element.width, element.height);
let endSize = element.toDataURL().length;
console.log(endSize);
}
}
fileReader.readAsDataURL(inputFile);
}
<input type="file" id="upload" name="image"/>
What's the reason?
One of the reasons is: You're trying to upload a jpg image, but when you're trying to make a copied version by:
const tempImage = new Image();
it really makes a new image with png format. You can check by downloading that copied version:
document.body.appendChild(tempImage);
That's why you have different sizes.
This question already has answers here:
DOMException when playing audio with blob as source
(2 answers)
How to get the image size (height & width) using JavaScript
(33 answers)
Getting BLOB data from XHR request
(4 answers)
Closed 3 years ago.
Im working in angular 7 and my requirement is i need to get Width, Height and Size (in how much kb or mb) of the image and also im trying to convert it into blob.
I tried with below code but im not getting exact output:
var img_url = "http://snook.ca/files/mootools_83_snookca.png";
var blob = new Blob([img_url]);
let reader = new FileReader;
reader.readAsDataURL(blob); // read file as data url
reader.onload = () => { // when file has loaded
console.log(reader.result)
var img:any = new Image();
img.src = reader.result;
img.onload = () => {
this.uploaded_image_width = img.width; //to get image width
this.uploaded_image_height = img.height; //to get image height
this.uploaded_image_url = reader.result; //to get blob image
console.log(reader.result)
};
}
When im consoling the blob data is coming wrong (console.log(reader.result)) and inside img.onload function is not executing.
I referred this fiddle to achieve this :
http://jsfiddle.net/guest271314/9mg5sf7o/
you can try like this way. i hope it helps you out
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = "http://lorempixel.com/output/city-q-c-250-250-1.jpg";
This question already has answers here:
How to save an image to localStorage and display it on the next page?
(8 answers)
Closed 6 years ago.
I have to make an image input that will not upload the image. The images will be used in another page where it will be edited(cropped and draw over) and then uploaded.
I don't know how to do that, do you have any ideas? I'll probably be using this plugin.
you have get the image using getElementByID. convert the image in to base64 and save in local storage
userimage = document.getElementById('imageId');
imageData = getBase64Image(userimage);
localStorage.setItem("imageData", imageData);
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
insert the script in your second page for getting the image from localstorage and set to the image src
window.onload = function() {
var getpicture = localStorage.getItem('imageData');
var image = document.createElement('img');
image.src = getpicture;
};
When I use image.width it returns the image's width which appears on the screen, and I use max-width property on the image and that image appears in some div. Real image's size is much bigger. Is it possible to get a real image's width?
You can get the real dimensions of an image by creating a new image with the same source and get the dimensions of that
var img = new Image();
img.onload = function() {
var w = this.width,
h = this.height;
}
img.src = $('img')[0].src; // or whatever
FIDDLE
First, know that images load asynchronously, meaning you'll have to write your code so you get the results in a callback function. Then, use a new image object with no explicit styling (so it can resize to fit native image dimensions) to trigger the callback. For example:
function whatWidth(url, onSize) {
var img = new Image();
img.src = url;
img.onload = function() {
onSize(img.width, img.height);
}
}
// Now get the dimensions of an image ...
whatWidth('http://icons.iconarchive.com/icons/deleket/keriyo-emoticons/256/Smiley-rofl-icon.png',
function(w, h) {
console.log('width x height: ', w, h);
}
);
// => Outputs "width x height: 256 256"
It's worth noting that, while this may appear to require a request to the server to fetch the image (independent from whatever image object you're actually showing on your web page), as long as the url is the same as the image on your page the browser cache will [typically] insure only one request is made.
Dart example with caching in case you need it (I know original question mentioned JS, but the logic stays the same):
class _IconSize {
final int width;
final int height;
_IconSize(this.width, this.height);
}
class IconLoader {
static final IconLoader _this = new IconLoader._init();
factory IconLoader() => _this;
// Url -> dimensions.
final Map<String, _IconSize> _cache = {};
IconLoader._init() {}
void withSize(String url, void onLoaded(int width, int height)) {
if (_cache.containsKey(url)) {
onLoaded(_cache[url].width, _cache[url].height);
} else {
final ImageElement img = new ImageElement();
img.onLoad.listen((_) {
var iconSize = new _IconSize(img.width, img.height);
_cache[url] = iconSize;
withSize(url, onLoaded);
});
img.src = url;
}
}
}
Turns out there's a naturalWidth property. Thanks w3schools!
You need to access it on the image's onload event
JS
var testImg = document.getElementById('testImg'),
iWidth=document.getElementById('width'),
iHeight = document.getElementById('height');
testImg.onload = function(){
console.log(this);
iWidth.value=this.width;
iHeight.value=this.height;
};
Here is the jsfiddle for it: http://jsfiddle.net/mac1175/evgP8/
Is there any technique to convert images that have already been downloaded – inline JPEG/GIF/etc. images that occur in a webpage – into Base64 data using client-side JavaScript?
I am not talking about how to transform an image into Base64 using other means (server-side, online tools, etc.).
These are the constraints for my particular use case:
The image is on screen now, right in the page, in front of person. It has already been downloaded in a data sense.
The conversion from raw image data has to be done client-side.
The images in question are from arbitrary domains. That is, they may or may not, be of same origin domain.
The user, if needed (if helpful to solution), can give additional permissions (for example, a FF toolbar install to help skirt cross-domain and other issues). That is, code can be given special endorsement on the client side if that helps solve the issue.
The end goal is to transform all images on the page (in the DOM) into Base64 data inside of JavaScript. Put another way, every image the user can see on the page has been converted into a JavaScript variable of some sort that contains the Base64 data.
So far I see no posts that stay inside of all the above constraints.
I think this is close to what you are looking for but the only problem is that it only works for locally hosted images and HTML5 only.
function toURL(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
var test = document.getElementById("myImage");
console.log(toURL(test));
You can trick javascript into thinking an image is from your domain with the following code.
image.php
<?php
$image = getAnImagePathAndTypeFromTheDatabaseByID($_GET["id"]);
//returns something like
//array("path" => "http://www.anotherwebsite.com/image.png", "type" => "png")
header("Content-type: image/$image[type]");
echo file_get_contents($image["path"]);
?>
Then just navigate to image.php?id=1 for example.
For it to work in cross-domain client-side you need to call the image with the attribute crossorigin = "true", or, add a line in the Logan Murphy code:
function toURL(image) {
image.setAttribute('crossOrigin', 'anonymous');
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
I use this code:
// image-to-uri.js v1
// converts a URL of an image into a dataURI
function imageToURI(url, callback) {
// Create an empty canvas and image elements
let canvas = document.createElement('canvas');
let img = document.createElement('img');
img.onload = function () {
let ctx = canvas.getContext('2d');
// match size of image
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
// Copy the image contents to the canvas
ctx.drawImage(img, 0, 0);
// Get the data-URI formatted image
callback(null, canvas.toDataURL('image/png'));
};
img.ononerror = function () {
callback(new Error('FailedToLoadImage'));
};
// canvas is not supported
if (!canvas.getContext) {
setTimeout(callback, 0, new Error('CanvasIsNotSupported'));
} else {
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
};
};
which is based on this https://github.com/HenrikJoreteg/image-to-data-uri.js/blob/master/image-to-data-uri.js