Reading width of an image using file reader? - javascript

I'm having issues reading sizes with file reader. Have tried various browsers and files, width always comes back as 0.
var fileReader = new FileReader();
var img = new Image();
fileReader.onload = function(event) {
img.src = event.target.result;
console.log(img.width);
};
fileReader.onerror = function() {
//handle error
};
fileReader.readAsDataURL(file);
The file var is looped out from the following on a drag and drop event:
e.originalEvent.dataTransfer.files

I think you have an error while assigning binary data to Image.
Assigning image:
fileReader.onload = function(e) {
var img = new Image();
img.src = fileReader.result;
}
Demo:
document.getElementById('img').addEventListener('change', function(e) {
var file = this.files[0];
var fileReader = new FileReader();
var img = new Image();
fileReader.onload = function(event) {
img.src = fileReader.result;
img.onload = function() {
console.log(img.width);
}
document.getElementById('result').appendChild(img);
};
fileReader.readAsDataURL(file);
})
<input id="img" type="file">
<div id="result"></div>
see codepen demo or jsfiddle

maybe your image object is not loaded try this :
img.onload = function () {console.log(img.width)}

Related

Show Image Canvas Javascript after upload files with File Reader

So I'm trying to display image on canvas using File Reader. But it won't work. I don't know where the problem is.
var canvas = document.getElementById("ourCanvas"),
context = canvas.getContext('2d'),
uploadedFile = document.getElementById('uploaded-file');
window.addEventListener('DOMContentLoaded', initImageLoader);
function initImageLoader() {
uploadedFile.addEventListener('change', handleManualUploadedFiles);
function handleManualUploadedFiles(ev){
var file = ev.target.files[0];
handleFile(file);
}
}
function handleFile(file) {
var imageType = /image.*/;
if(file.type.match(imageType)){
var reader = new FileReader();
reader.onloadend = function(event) {
var tempImageStore = new Image();
tempImageStore.onLoad = function(ev){
canvas.height = ev.target.height;
canvas.width = ev.target.width;
context.drawImage(ev.target, 0, 0);
}
tempImageStore.src = event.target.result;
}
reader.readAsDataURL(file);
}
}
After I upload the file, image don't show on the Canvas, and does'nt show anything wrong in Console. Is there any problem with my code?

Convert Image uri into Base64 [duplicate]

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.
The code I am using:
var imagepath = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image url to BASE64?
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to #Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
The MDN reference of HTMLCanvasElement.toDataURL().
And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by #HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

Two same images displayed at the same time

I am using Fabric js to do image manupulation drag, resize and merge images onto the one image onto the canvas but it shows one bug, i.e when I upload the image it displays two same images at a time, while i need only one.
Please help me to solve this issue.
My code is:
var canvas = new fabric.Canvas('imageCanvas', {
backgroundColor: 'rgb(240,240,240)'
});
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
scaleX: 0.2,
scaleY: 0.2
})
canvas.add(imgInstance);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}

Convert image from url to Base64

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.
The code I am using:
var imagepath = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image url to BASE64?
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to #Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
The MDN reference of HTMLCanvasElement.toDataURL().
And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by #HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

How to display an image from a file input? [duplicate]

This question already has answers here:
Preview an image before it is uploaded
(29 answers)
Closed 8 years ago.
I would like to choose a file and display the image on the browser.
I tried inserting the direct image path and it worked.
The problem now is, how can I display the image from the <input type=file> ?
Here is what my code looks like:
function myFunction() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.onloadend = function {
var image = document.createElement("img");
image.src = "reader"
image.height = 200;
image.width = 200;
document.body.appendChild(image);
}
}
<input type=file name=filename id=file>
<button type=button onclick='myFunction()'>Display</button>
function myFunction() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
// it's onload event and you forgot (parameters)
reader.onload = function(e) {
var image = document.createElement("img");
// the result image data
image.src = e.target.result;
document.body.appendChild(image);
}
// you have to declare the file loading
reader.readAsDataURL(file);
}
http://jsfiddle.net/Bwj2D/11/ working example
be carrefull : reader.onloadend = function {
must be reader.onloadend = function() {
but why use a fileReader ?
For exemple my function to add pictures in my webSite =>
function createImageBase(src, alt) {
var image = document.createElement('img');
image.src = src;
image.alt = alt;
return image;
}
function addPicture(targetID, imageSRC){
var location = document.getElementById(targetID);
var image = createImageBase(imageSRC, imageSRC);
location.appendChild(image);
}
Then just call it like that :
Display

Categories