Create base64 encoded images with JavaScript - javascript

Since images are data, we can write our code as
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
Now my point is: can we create that base64 data with javascript? Is there any framework for it?
My actual requirement is that I have a string like "Cow" and I want it as an image.
Note: I do not want a server call for it. I know I can call server side code by passing "Cow" as a parameter. My server side code can generate that image, but I want do this from the browser with JavaScript.

You can create an image with canvas. There are many canvas frameworks which can help you. Then you can "export" your canvas to base64 string.
Try this sample with jCanvas:
HTML
<p>
Result:
</p>
<p>
<textarea id="result" cols="60" rows="10"></textarea>
</p>
<p>
<input id="click" type="button" value="Convert to base64">
</p>
<p>
Canvas<br><canvas id="myCanvas" width="100" height="100"/>
</p>
JavaScript
$(function(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 80, 80);
$('#click').click(function() {
$('#result').html($("canvas").getCanvasImage());
});
});
Demo

I hope I got your question right. You want the actual data and not the uri??
I found this small snippet from MuniR, I think it is what you wanted.
The thing is we cannot seem to get away from the canvas, create it with the size of the image, paint the image and use the canvas object to store it!!-Not necessarily USE it... Hope it helps, and good luck
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = url;
}

var element = new Image();
element.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
If you wants to add id to your body:
document.body.appendChild(element);
You have to use appendChild on the parent element of where you want to display the image. It will be automatically loaded.

Related

Creating image from two other images using javascript [duplicate]

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

change image from path to embedded

I have an html image
<img src="/path/to/my/image.png" />
I want the same content, but as an embedded image
<img src="data:image/png:base64/xyzafasfasfafasfafasfasag">
can I do this transformation easily with Javascript?
html: <img src="/path/..." id="image">
js: document.getElementById('image').src = 'data:image/png:base64/qweqwe...';
Found the solution myself:
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,img.width,img.height);
// 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");
return dataURL;//.replace(/^data:image\/(png|jpg);base64,/, "");
}

getting html canvas image as javascript object

I want to get html canvas image as javascript object. I looked samples from internet. But all samples are getting images from a source to canvas like this:
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
</body>
But my problem: There is an image on canvas element that created by pencil. I want to get that image as object and post to server. But I could not get.
have you tried canvas.toDataURL()?
more hardcore way might be canvas.getContext('2d').getImageData() would return ImageData object.

canvas to image shows as no image (blank)

I'm working on converting a canvas to an image using dataurl. I have the following code that outputs no error in console. Seems to work somewhat, but when i access the dataurl it shows a blank image.
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
var myImage = context.drawImage(imageObj, 0, 0);
var myImg = canvas.toDataURL("image/png");
document.getElementById("canvasimg").setAttribute("src", myImg);
};
imageObj.src = "http://img801.imageshack.us/img801/5641/3cc67ca1a74049ce99bc92b.png";
};
<canvas id="myCanvas" width="578" height="400"></canvas>
<img id="canvasimg" alt="" src="">
Look at what you are doing. You are drawing the image when the image loads, but you are converting it to a data url before the image has been drawn! Move that toDataURL call and the setAttribute call INSIDE the onload function.
Testing the code you have posted, I get a Security Error raised. Which is to be expected. The canvas has a clean-origin flag, and once that flag is false, you can't pull data out of it.
Here's a more detailed, related question
Documentation linked to in the answer

Can you combine multiple images into a single one using JavaScript?

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

Categories