Base64 png to Canvas - javascript

I'm struggeling with drawing a image on a Canvas.
What I have done so far is that I have inserted imagedata from a Canvas into a database.
The problem is that when I try to create an image of the data and draw it back on the Canvas later it does not draw the same, only some pixels may be drawen while the rest is just blank like nothing should be drawen there.
I'm getting the image data like this:
var CanvasData = document.getElementById('canvas');
CanvasData = CanvasData.toDataURL("image/png");
And drawing the image back on the Canvas like this (the data is stored in a database):
var result = xmlhttp.responseText;
var CanvasDraw = document.getElementById('canvas');
var ctxChange = CanvasDraw.getContext('2d');
imagedata = new Image();
imagedata.src = result;
imagedata.onload = function(){
ctxChange.drawImage(imagedata, 0, 0);
}
Here's a link to pastebin for an example of imagedata: http://pastebin.com/XGmV49k9
Result is the data that is returned from a AJAX call and is the same as what is stored in the database.
Thanks for any help.

Seems that error in this line:
imagedata.src = result;
Should be:
imagedata.src = CanvasData;

Related

create image data in javascript

I want to create a black (or white, I really don't care the "colour") 1x1px image in javascript, I tried doing it with var img = new Image(1,1) but I don't know how assigng the source of the image with img.src to be all black (I don't want to use a file, I want to be generated with JS code).
There is a way to do that?
You can also use base64 encoded data in the image.src.
var image = new Image(10, 10);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
document.body.appendChild(image);
I found it:
var image = document.createElement('canvas').getContext('2d').getImageData(0,0,1,1);
I'll let question open to know if there is another way to do it.
Sources I used:
CanvasRenderingContext2D.createImageData()
CanvasRenderingContext2D.getImageData()
Similarly you can perform the image manipulation in canvas, then pass a data URI containing a representation of the image over to the HTML image for actual rendering.
const imgWidth = 1;
const canvas = document.createElement("canvas");
canvas.width = imgWidth;
canvas.height = imgWidth;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,imgWidth,imgWidth);
const url = canvas.toDataURL();
const newImg = document.createElement("img");
newImg.src = url;
document.body.insertBefore(newImg, null);

Cropping data:image/png;base64 for large print screens

I'm trying to crop large print screens added in contenteditable by ctrl+v. Have tried several ways but I can't get it to work. The last methode I tried is the drawImage that's why I left it inside the code. Think i'm on the wright direction with it? Or do I need a totally other technique?
I want to use the data:image/png;base64 to store it inside the database. But with very large print screens it's to large to store in the database. Any suggestions? Thanks in advance!
Edit: I just noticed that I need to use blob field in database instead of text. This fixed the issue to store larger screenshots in database. But still do people have any advice for the use of blob and store it in database? I think cropping large screenshots would still be an improvement?
document.onpaste = function(pasteEvent) {
var item = pasteEvent.clipboardData.items[0];
if (item.type.indexOf("image") === 0) {
//pasteEvent.preventDefault();
//alert('You can\'t copy & paste images or screenshots yet.');
var blob = item.getAsFile();
var reader = new FileReader();
var size = pasteEvent.clipboardData.files[0].size;
alert(size);
//var canvas = reader;
//var context = canvas.getContext('2d');
//canvas.width = canvas.height = 64;
//context.drawImage(img, 64,64, 64, 64, 0, 0, 64, 64);
//mod.src = canvas.toDataURL();
reader.onload = function(event) {
document.getElementById("container").src = event.target.result;
};
reader.readAsDataURL(blob);
}
if (item.type.indexOf("text") === 0) {
pasteEvent.preventDefault();
const text = pasteEvent.clipboardData.getData('text');
document.execCommand("insertHTML", false, text);
}
}
I guess these lines of code will work
var canvas = reader;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0, canvas.width, canvas.height);
mod.src = canvas.toDataURL();
Thanks

Load file into IMAGE object using Phantom.js

I'm trying to load image and put its data into HTML Image element but without success.
var fs = require("fs");
var content = fs.read('logo.png');
After reading content of the file I have to convert it somehow to Image or just print it to canvas. I was trying to conver binary data to Base64 Data URL with the code I've found on Stack.
function base64encode(binary) {
return btoa(unescape(encodeURIComponent(binary)));
}
var base64Data = 'data:image/png;base64,' +base64encode(content);
console.log(base64Data);
Returned Base64 is not valid Data URL. I was trying few more approaches but without success. Do you know the best (shortest) way to achieve that?
This is a rather ridiculous workaround, but it works. Keep in mind that PhantomJS' (1.x ?) canvas is a bit broken. So the canvas.toDataURL function returns largely inflated encodings. The smallest that I found was ironically image/bmp.
function decodeImage(imagePath, type, callback) {
var page = require('webpage').create();
var htmlFile = imagePath+"_temp.html";
fs.write(htmlFile, '<html><body><img src="'+imagePath+'"></body></html>');
var possibleCallback = type;
type = callback ? type : "image/bmp";
callback = callback || possibleCallback;
page.open(htmlFile, function(){
page.evaluate(function(imagePath, type){
var img = document.querySelector("img");
// the following is copied from http://stackoverflow.com/a/934925
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.
window.dataURL = canvas.toDataURL(type);
}, imagePath, type);
fs.remove(htmlFile);
var dataUrl = page.evaluate(function(){
return window.dataURL;
});
page.close();
callback(dataUrl, type);
});
}
You can call it like this:
decodeImage('logo.png', 'image/png', function(imgB64Data, type){
//console.log(imgB64Data);
console.log(imgB64Data.length);
phantom.exit();
});
or this
decodeImage('logo.png', function(imgB64Data, type){
//console.log(imgB64Data);
console.log(imgB64Data.length);
phantom.exit();
});
I tried several things. I couldn't figure out the encoding of the file as returned by fs.read. I also tried to dynamically load the file into the about:blank DOM through file://-URLs, but that didn't work. I therefore opted to write a local html file to the disk and open it immediately.

How to save and load HTML5 Canvas to & from localStorage?

I want the user to be able to save canvas drawings to the localStorage (using the Save button)under a custom name and then be able to load (using the load button) previous drawings from the localStorage.
First option
If you want to save just a bitmap then you can save it this way:
localStorage.setItem(canvasName, canvas.toDataURL());
and then load like this:
var dataURL = localStorage.getItem(canvasName);
var img = new Image;
img.src = dataURL;
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
I recommend to use canvas.toDataURL() instead of ctx.getImageData() because ctx.getImageData() JSON string size will be just enormous even if canvas is empty.
Second option
If you want to store canvas as lines array then you should store lines coords in some variable and save it`s json:
localStorage.setItem(canvasName, JSON.stringify(linesArray));
Then you can load lines array and redraw canvas:
var lines = JSON.parse(localStorage.getItem(canvasName));
lines.forEach(function (line) {
ctx.beginPath();
ctx.strokeStyle = line.color;
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.stroke();
});
First step will be to get image data from canvas.
var imageData = myCtxt.getImageData(0,0,WIDTH,HEIGHT);
Now store it to localStorage after stringifying it:
localStorage.setItem(savekey, JSON.stringify(idt));
To read and set the data back you can use following:
var idt = localStorage.getItem(savekey) || null;
if (idt !== null) {
var data = JSON.parse(idt);
ctx.putImageData(idt, 0, 0);
}
I have put the functions to handle the functionality in your fiddle.
Regarding localStorage you can read this and this questions.

Restore canvas with base64 string

Whenever i first loaded the page. The image doesn't get restored but once i load the page and i hit F5. then it works. i'm not where whats wrong with my code.
// variable r contains the base64 string which is retrieved via a ajax call.
var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(myImage, 0, 0);
Ok. Instead of calling the ajax automatically when the page is loaded, i manually triggered the ajax call via a button, still i get the same result.
The base64 strings is retrieved successfully and imaged is not loaded. but when i clicked the button for a second time. the image is than loaded.
var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// wait for it to load before calling draw
myImage.onload = function() {
ctx.drawImage(myImage, 0, 0);
}

Categories

Resources