Saving image to localstorage - canvas - javascript

I'm using html5 storage to store my image.
It works great in chrome. In FireFox it works 8/10 times.
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);
console.log("line 1 : " + img.src);
var dataURL = canvas.toDataURL('image/jpeg');
console.log("line 2 : " + dataURL.replace(/^data:image\/(jpeg);base64,/, ""));
return dataURL.replace(/^data:image\/(jpeg);base64,/, "");
}
Sometimes it returns only "data,".
I see that the canvas size is 0x0:
canvas.width = img.width;
canvas.height = img.height;
Why is that happening?

If the height or width of the canvas is 0, the string "data:," is returned.
This is most likely the cause for some images to fail to receive a proper dataUrl.
Check your img elements and/or scripts to obtain and set the width and height of the canvas.
The auto width and height are only available after the image is loaded.

The function is trying to get the height/width before the image is loaded so I get 0x0. To solve that add img.onload before calling the save function.
function readURL(input, image, width, height) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//Save the image
var img = new Image();
img.src = e.target.result;
img.onload = function (e){
if (image.id == 'photo1') {
save(img, 'image1');
}
else {
save(img, 'image2');
}
}
}
reader.readAsDataURL(input.files[0]);
}
}

Related

Image dimensions not reflected correctly

I am trying to get the base64 of some images in Javascript and was using this function:
function getBase64Image(img) {
return new Promise((data) => {
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data(canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
})
}
Then I call the function to load in the image using:
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
getBase64Image(this).then(data => {})
}
img.src = wha[1][0]
If I look at the naturalWidth of the image (96px), it is different from the actual image itself (640px). I had been looking at other methods of getting base64 from an image but they also return the same results.

Chrome javascript image to canvas causes empty image

Converting image to the canvas with canvas.drawImage fails(but not throws err), the canvas looks transparent empty image
It doesn't happen for all image files I could not figure out which property of the image causes this but I uploaded an example photo with this issue
I started having this problem with chrome v83-v84
firefox works fine.
I want to upload a specified photo (its inside fiddle) and want to make canvas and draw canvas from the uploaded image and display it on chrome (chrome version should bigger or equal v85)
function testimg(src) {
var img = document.createElement("img");
img.src = src;
document.querySelector('#test').appendChild(img)
}
$('#file').on('change', fileAdded)
function fileAdded(event) {
var reader = new FileReader;
reader.onload = function () {
var image = new Image();
image.src = reader.result;
image.onload = function () {
document.querySelector('#test').appendChild(this)
var imgToSend = processImg(this, this.width, this.height);
testimg(imgToSend)
};
};
reader.readAsDataURL(event.currentTarget.files[0]);
}
function processImg(image, srcWidth, srcHeight) {
var canvas = document.createElement('canvas');
canvas.width = srcWidth;
canvas.height = srcHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
ctx.fill();
return canvas.toDataURL();
}
https://jsfiddle.net/msacar/2Lgmc85t/24/

Can't get base64 resized image from javascript canvas

I have two main questions. I'm trying to resize a base64 image according to the answer in
JavaScript reduce the size and quality of image with based64 encoded code
This seemed simple enough, except for the fact that I need to get only the base64 string from that function, without the data:image... header.
I tried to modify the function like this:
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
context.scale(width / this.width, height / this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
var result = canvas.toDataURL();
return result.substr(result.indexOf(",") + 1)
}
which returns a base64 string. This string is corrupted, and it never displays correctly. Why is this happening and how can I fix it?
The other question is, is there a way to resize the image based on percentage and not on pixel size?
Thanks
I ended up rewriting the function based on another canvas function I found. This function takes the src of a base64 img, modifies the size and assigns the result in base64 to another element:
function resizeBase64Img(url, width, height) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.scale(width/this.width, height/this.height);
ctx.drawImage(this, 0, 0);
result=canvas.toDataURL();
$('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));
};
img.src = url;
}
And it should be invoked like this:
resizeBase64Img($('#image').attr('src'),300,300);

Image not getting copied properly in javascript

I need images to be copied and sent to server for image rotations etc.
To copy an image I'm using this code( from Get image data in JavaScript?):
function getBase64Image(img) {
// Create an empty canvas element
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");
var replaced = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log("dataurl=",dataURL);
console.log("replaced=",replaced);
return replaced;
}
It is called like this:
$("#xyz").load(send_image).each(function () {
if (this.complete)
$(this).load();
});
function send_image(){
getBase64Image(document.getElementById('xyz'));
}
However in getBase64Image function once in 40-50 times dataURL is being returned as empty.
What could be the reason?

Javascript FileReader eats up all the memory when reads local images

I'm working on a concent to show the thumbnail of a large number of images from the local drive.
With HTML5 File API is seems quite possible, but whn I try to load a big number of images the memory usage of the browser goes over the roof and the collapses.
I think the problem is that the FileReader doesn't releases the memory after a file read.
Originally I had a new instance of FileReader and a simple loop to iterate through the images.
To solve this memory problem I replaced this to have one FileReader only, but it did not really help.
Here is the relevand code block:
<script>
var areader = new FileReader();
var counter=0;
function loadImage(file) {
var canvas = document.createElement("canvas");
areader.onload = function (event) {
var img = new Image;
img.onload = function () {
canvas.width = img.width / 100;
canvas.height = img.height / 100;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width / 100, img.height / 100);
var browse = document.getElementById("uploadInput");
if (browse.files.length > counter) {
counter++;
areader.result = null;//I don't think this makes any difference
loadImage(browse.files[counter]);
}
};
img.src = event.target.result;
};
areader.readAsDataURL(file);
preview.appendChild(canvas);
}
function showImages() {
loadImage(document.getElementById("uploadInput").files[0]);
}
If anybody come across this problem the I do something very stupid could you reply.
Thanks,
Tamas
It's not the file reader but you are using the entire image's data in base64 as the src property of the image, which will actually take 133% of the image's size in memory.
You should use Blob URLs instead:
var URL = window.URL || window.webkitURL;
function loadImage( file ) {
var canvas = document.createElement("canvas"),
img = new Image();
img.onload = function() {
canvas.width = img.width / 100;
canvas.height = img.height / 100;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width / 100, img.height / 100);
URL.revokeObjectURL( img.src );
img = null;
var browse = document.getElementById("uploadInput");
if (browse.files.length > counter) {
counter++;
loadImage(browse.files[counter]);
}
};
img.src = URL.createObjectURL( file );
preview.appendChild(canvas);
}

Categories