Show Image Canvas Javascript after upload files with File Reader - javascript

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?

Related

Why is image uploader not working on chrome?

I have a button where you can upload an image and insert it in a tag, it works on every browser but not on chrome. The first reader.onloadend is processed, I can log image and image.src.
var inputUpload = document.getElementById('buttonUpload');
inputUpload.addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
//Initiate the JavaScript Image object.
var image = new Image();
image.src = reader.result;
console.log('image.src');
image.onloadend = function() { /* execution stops here */
var height = this.height;
var width = this.width;
if (height > 150 || width > 150) {
showAlert('Image dimensions must be within 150×150 pixels.');
} else {
// convert file to base64 String
const base64String = reader.result.replace('data:', '').replace(/^.+,/, '');
// display image
valueImg = "data:image/png;base64," + base64String;
updateImg(valueImg);
};
};
};
reader.readAsDataURL(file);
});
<button id="buttonUpload" type="button" class="d-inline btn-custom mx-0">
Upload
</button>
When I select the image file, it stops at image.loadend but I get no errors in the console

How to load image files, each into their own canvas element

I tried to load images into several canvas elements, but only the last image was loaded from the list of files. I need different images in different canvas elements, each in its own. Thanks for help.
HTML
<input type='file' id='imgfile' multiple />
The canvas element will be created by jQuery.
JavaScript
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input, fr, file, img;
input = document.getElementById('imgfile');
$.each(canvas, function(i, v) {
file = input.files[i];
fr = new FileReader();
fr.onload = function createImage() {
img = new Image();
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img, 0, 0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}
$("input").change(function() {
var picture = this.files;
var leng = picture.length;
for (var i = 0; i < picture.length; i++) {
$("input").after('<canvas width="50" height="50" style="border:1px solid red"></canvas>');
}
loadImage();
});
You need to declare variables inside iteratee function
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input = document.getElementById('imgfile');
$.each( canvas, function( i, v) {
var file = input.files[i];
var fr = new FileReader(); // file reader per file
fr.onload = function createImage() {
var img = new Image(); // image per file
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img,0,0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}

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]);
}

Canvas drawImage is not accepting width and height

Image is getting created in full original size, even last two arguments 150, 150 are height and width context.drawImage(img, 0, 0, 150, 150); in the code below:
function (file) { //uploaded files are always images
var reader = new FileReader(); //FileReader for uploading files from local stroge.
reader.onload = function () {
var links = document.createElement('a'); //link when image is clicked
var img = document.createElement('img');
img.src = reader.result; //src = url from uploaded file
img.className = 'images'; //css -> .images { margin-top: 30px; padding: 30px; }
img.onload = function () { //repaint image to 150 - 150 size with canvas, because setting width and height on image itself would just resize the image but I want to create new image with new size
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, 150, 150) //draw image with canvas
}
links.href = reader.result; // url from local storage needed when image is clicked -
links.target = "_blank"; // open new blank page with original image
links.appendChild(img); // image is appended to <a>
document.body.appendChild(links); // <a> is appended to body, that body contains image thumbnail with a link linked to the image source
}
if (file) {
reader.readAsDataURL(file); // read uploaded files url
}
}
img.onload does not making any sense here. result is the same even when I remove it.
You are not drawing back the cropped image to your <img> tag... you will have to create two image Objects, let's call the first originalImage, and the second one croppedImage.
The one you will append to the document is croppedImageand originalImage will just stay in the cache.
When originalImage has loaded, you will paint it to a canvas, and then set croppedImage to the result of the canvas' toDataURL() method.
var read = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var links = document.createElement('a');
// this will be the appended image
var croppedImage = new Image();
// do your DOM stuff
croppedImage.className = 'images';
links.href = reader.result;
links.target = "_blank";
links.appendChild(croppedImage);
document.body.appendChild(links);
// create a buffer image object
var originalImage = new Image();
// set its load handler
originalImage.onload = function() {
// create a canvas
var canvas = document.createElement('canvas');
// set canvas width/height
canvas.width = canvas.height = 150;
var context = canvas.getContext('2d');
// draw the buffered image to the canvas at required dimension
context.drawImage(originalImage, 0, 0, 150, 150);
// set the appended to doc image's src to the result of the cropping operation
croppedImage.src = canvas.toDataURL();
}
originalImage.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
}
};
upload.onchange = read;
.images {
margin-top: 30px;
padding: 30px;
}
<input type="file" id="upload" />
You could also have used only a single image object, but this would have required to reset the onload event in the onload event, to avoid an infinite loop, which is a little bit less clear :
var read = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var links = document.createElement('a');
var img = new Image();
img.className = 'images';
links.href = reader.result;
links.target = "_blank";
links.appendChild(img);
document.body.appendChild(links);
img.onload = function() {
//reset the onload event so it does fire in a loop
img.onload = function(){return;};
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 150;
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, 150, 150);
this.src = canvas.toDataURL();
}
img.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
}
};
upload.onchange = read;
.images {
margin-top: 30px;
padding: 30px;
}
<input type="file" id="upload" />
var reader = new FileReader();
reader.onload = function () {
var links = document.createElement('a');
var img = new Image();
img.src = reader.result;
img.className = 'images';
img.onload = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, 150, 150);
this.src = canvas.toDataURL(); // convert the canvas back to the image
links.appendChild(this); // append the updated image to the document
}
links.href = reader.result;
links.target = "_blank";
document.body.appendChild(links);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
}

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