set background-image from localStorage base64 string - javascript

I have a function that encodes an image into base64 string and stores it into localStorage. I am trying to retrieve the image from localStorage and use it to set a background-image with jQuery.
Everything is working right, but the image isn't displaying. When I inspect the element in the browser, the single quotes around the 'data' uri aren't being inserted. I don't know if this is the problem or not.
Here is my code
function to encode and store image:
var img = document.getElementById("elephant");
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
return dataURL;
}
jQuery to set the image:
localStorage.setItem("background" , getBase64Image(img));
console.log(localStorage);
background = localStorage.getItem("background")
console.log(background);
$("#elephant2").css('background-image' , 'url(' +background+ ')');

I thought the issue was missing quotes, but it was actually corrupted/incomplete base64 data string. I placed the function inside window.onload = function () so the image loaded entirely before converting to a string and it works like a charm/

Related

Can I store image as blob to localstorage or somewhere so it can used in another page?

I am using Cordova's camera plugin to get a Picture (getPicture() method). It returns the picture taken in blob url format. I am saving the blob url of the image in a key of an object that I am saving in the LocalStorage. However, the problem is that when I retrieve the blob url from local storage and set the image's src on another page, the image is not displayed. It is displayed as shown in the image below.
I read somewhere that this is because blob urls are only valid for the page they were generated on. Is there a way I can make the generated image usable on another page?
What I do is, convert image in Base64 string and then store that Base64 string to localstorage.
For Ex
Get image by id and store image to localstorage
image = document.getElementById('myImage');
imgData = getBase64Image(image);
localStorage.setItem("imgData", imgData);
Base64 Conversion
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,/, "");
}
Then on any next page or same page you can retrieve Base64 image from localstorage and display to page
var dataImage = localStorage.getItem('imgData');
imageTag = document.getElementById('myImage');
imageTag.src = "data:image/png;base64," + dataImage;

Getting blank image with canvas draw about half the time

I am converting a base64 string into an image, and then passing it to a canvas draw to make it smaller. This is based off a script I found on SO.
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL();
}
I pass in the image element (which is correct before, I've checked), and some of the time this script works correctly and changes the image to the correct size, and other times it generates what I think is a blank image, like this:
iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAAAEJJREFUaAXt0IEAAAAAw6D5Ux/khVBhwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYeBwYnQgABzCacsQAAAABJRU5ErkJggg==
I can't find any reproducability - it happens or it doesn't, on the same or different images.
What could be going on? The script seems to work, but only half the time? Everything else is being kept exactly the same.
Edit - this is how the image for the above function is being generated:
function resizeURI(base64) {
var img = new Image;
// turns base64 into dataURI
var uri = base64ToDataUri(base64);
img.src = uri;
var resizedURI = resizeImage(img);
// turns dataURI into base64 again
resizedURI = resizedURI.substring(resizedURI.indexOf(",") + 1);
return resizedURI;
}
function resizeImage(img) {
var newDataUri = imageToDataUri(img, 50, 50);
return newDataUri;
}
The reason is because the image is not always loaded when the imageToDataUri is called. you should wait for it to be fully loaded, by adding event listener, and wait for "loaded" event before you call imageToDataUri().
see HTML5 canvas - drawImage not always drawing the image

jsPDF Incomplete or corrupt PNG file

Adding regular png images was no problem with jsPDF, but now i send a generated image from my server and the browser console displays this error when rendering the PDF file:
Incomplete or corrupt PNG file
obviously the image is not incomplete or corrupt because i can see the response from the server and the image is fine.
Also to avoid render the pdf file before the image is ready i make a check to a that holds the image value variable if is undefined/null.
the format of my image is
var image = "data:image/png;base64,iVBORw0KGgoAAAANSUh...etc";
What could be the problem?
Edit: i changed the format of the image to jpg and this error shows
Supplied data is not a JPEG
if i use this library jspdf.plugin.addimage.js the images are rendered correctly but not the png images.
edit: 2 i made a solution modifying the jspdf.plugin.addimage.js file function addImage, i just changed the name of the function and added those generated images to pdf with that function, since the version of jspdf.min.js has the same name for the same function with this way it won't override the function i can use the one that works with normal images and the ones generated by the server.
This type of error occurs because the image has not finished loading when you send to jsPdf, use onLoad event to check the image loaded completely. for Example -
/* where src = full image url
callback = is callback function
outputFormat = image output format */
function toDataUrl(src, callback, outputFormat) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
/*image completely converted to base64string */
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
/* call back function */
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = appConfig.config.dummyImage;
img.src = src;
}
}
function callbackBase64(base64Img)
{
/*base64Img contains full base64string of image */
console.log(base64Img);
}
call above function and get base64string of image -
toDataUrl('http://example1.com/image1.jpg', callbackBase64(base64Img), "image/png");

Javascript convert image to PNG

After seing alot of examples here, and try to use them they work in some degree, but it doesn't true convert the image.
The image as the extension now png and open as such, but if I go into properties it stills says :
on C# and HTML the image shows without any problem, but I'm using the language c++ and it won't show on the QPushButton
This is an example of the code that I'm using on the javascript to convert the image:
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
So the image is saved throught base64 to png opens as such on many programs but on the one that I'm trying to do it wont.
How to I properly convert an image to png ?! Since this method isn't working

Javascript: loading image from bytearray

In Javascript you have the ByteArray type and some views on it as described here:
https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays
is it possible to store image data in such bytes and if yes, how can i display such an image? png or jpg?
Yes, you can store an image using the typed arrays.
Im not sure what you want actually.
If you want to create an HTMLImageElement from a ByteArray, you can do something similar as cited in here and here.
If you want to get the bytes from an Image, that would be trickier. You can draw the ImageElement to HTML canvas, and them get the URI back using toDataURL.
I just tried to get the data using canvas and it worked.
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
myCanvas.width = img.width;
myCanvas.height = img.height;
ctx.drawImage(img,0,0); // Or at whatever offset you like
alert(myCanvas.toDataURL());
};
img.src = "logo4w.png";
Although, the method toDataURL() do not allow you to perform this operation if the image you draw on canvas comes from outside the website domain.

Categories

Resources