How to convert dataurl back to image and display on canvas - javascript

I have 3 canvases. I crop a region from canvas1 and display it on canvas 2 . Then I want to convert canvas 2 image to a URL and to see if can convert that URL back to a image. I want it to be displayed in canvas c4.Any help is appreciated.
// image is drawn here , I want this image to be converted to a dataURL
//then back to image and display it in canvas c4
var c2 = document.getElementById("area_c2");
var ctx = c.getContext("2d");
var ctx2 = c2.getContext("2d");
image_src.width = c2.width;
image_src.height = c2.height;
ctx2.drawImage(image_src, 0, 0,image_src.width, image_src.height);
var c4 = document.getElementById("area_c4");
var ctx4 = c4.getContext("2d");
var dataURL = c2.toDataURL();
var myImg = new Image;
myImg.src = dataURL;
myImg.width = c4.width;
myImg.height = c4.height;
ctx4.drawImage(myImg, 0, 0, image_src.width, image_src.height); //Image //is not displayed here , I want the image to take the size of the canvas
<canvas id ="area_c2" style="width:300px;height:300px;border:3px solid
black;z-index:1" >
</canvas>
<canvas id ="area_c4" style="width:300px;height:300px;border:3px solid
black;z-index:1;background:red">
</canvas>

The reason your solution did not work is because you did not wait for the onload event. Before the onload event the image will not render.
To convert a canvas to a data URL is simple, use the .toDataURL(); method of the canvas element.
Then to convert the data URL back to an canvas image, you would first have to create an Image element and set its source as the dataURL. After getting the image onload event you can draw the image onto the canvas. This could be accomplished as shown:
Assuming the data URL is in a variable called dataURL, the canvas context is in a variable called ctx.
var img = new Image;
img.onload = () => { ctx.drawImage(img, 0, 0); };
img.src = dataURL;
The final solution would go like this:
var cdata2 = c2.toDataURL();
var cimg2 = new Image;
cimg2.onload = () => { ctx4.drawImage(cimg2, 0, 0, c4.width, c4.height); };
PS: You don't have to scale the image object by specifying the width and height, the canvas will do that when you specify the destination width and height.

Related

Overlay two base64 image url and save them as single image in Javascript

I have a whiteboard option during a video call in my web application built in angularjs (1.x). Users can draw above the video in a canvas element. I need to take a screenshot of the current video position and drawing on the canvas. I am able to get the video frame as base64 URL(second image) and canvas drawing as base64 URL(third image) separately. But I need to get it as a combined single image in base64 URL like the first image.
HTML
<img id="img1">
<img id="img2">
<canvas id="mergedImage" width="382" height="510"></canvas>
JS
var drawingImg1 = document.getElementById('img1');
drawingImg1.setAttribute('src', img1);
var drawingImg2 = document.getElementById('img2');
drawingImg2.setAttribute('src', img2);
var c = document.getElementById('mergedImage');
var width = 382;
var height = 510;
var ctx = c.getContext("2d");
var imageObj2 = new Image();
imageObj2.onload = function (){
ctx.drawImage(imageObj2, 0, 0, width, height);
var imageObj1 = new Image();
imageObj1.onload = function (){
imageObj1.style.objectFit = "cover";
ctx.drawImage(imageObj1, 0, 0,width, height);
};
imageObj1.src = img2;
};
imageObj2.src = img1;
I tried the above code and it gives the output as video frame image only not the drawing included.
I want the output as the first image. Please, someone, guide me to do this.
I have created a jsfiddle here
The following solution worked for me to overlap 2 images and got a single image in a canvas.
Link

Get frame from Img tag with a url source in Javascript

I have a img tag in my html
<img width="600px" height ="400px" id='the_img_1' src='http://127.0.0.1:5000/video_feed'>
Img element is displaying the video from a local url.
I want to get a frame(or image in jpg form) of video from this img tag in javascript. Is this possible?
I hope this will help you this is exactly what you want this is not the best way but it is as per your requirement:
var imgTags = document.getElementsByTagName('img');
for(i=0; i<imgTags.length; i++){
var iframurl = imgTags[i].getAttribute("src");
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(iframurl);
document.body.appendChild(iframe);
}
<img width="600px" height ="400px" id='the_img_1' src='http://127.0.0.1:5000/video_feed'>
Use canvas.
1. Draw img tag contents on canvas
2. get DataUri from canvas (encoded base64 string)
var img = document.getElementById("the_img_1");
var canvas = document.getElementById('myCanvas') // reference to canvas element
var ctx = canvas.getContext('2d'); // get the canvas context;
ctx.drawImage(img, 0, 0, 640,480); //draw image into canvas;
encodedImg = canvas.toDataURL("image/png");

Convert SVG dataUrl to base64

I'm using a plugin (dom-to-image) to generate a SVG content from a div.
It returns me a dataURL like this:
data image/xml, charset utf-8, <svg...
If a put this on a <img src the image is shown to normally.
The intent is to grab this dataURL, convert it to base64 so I can save it as an image.png on a mobile app.
Is it possible?
I tryied this solution https://stackoverflow.com/a/28450879/1691609
But coudn't get to work.
The console fire an error about the dataUrl
TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.
==== UPDATE :: PROBLEM EXPLANATION/HISTORY ====
I'm using Ionic Framework, so my project is an mobile app.
The dom-to-image is already working cause right now, its rendering a PNG through toPng function.
The problem is the raster PNG is a blurry.
So I thought: Maybe the SVG will have better quality.
And it IS!! Its 100% perfect, actually.
On Ionic, I'm using 2 step procedure to save the image.
After get the PNG generated by the dom-to-img(base64) dataURL, I convert it to a Blob and then save into device.
This is working, but the final result, as I said, is blurry.
Then with SVG maybe it will be more "high quality" per say.
So, in order to do "minimal" change on a process that s already working :D I just need to convert an SVG into base64 dataURL....
Or, as some of you explained to me, into something else, like canvas...
I don't know any much :/
===
Sorry for the long post, and I really, really thank your help guys!!
EDIT COUPLE OF YARS LATER
Use JS fiddle for a working example: https://jsfiddle.net/msb42ojx/
Note, if you don't own DOM content (images), and those images don't have CORS enabled for everyone (Access-Control-Allow-Origin header), canvas cant render those images
I'm not trying to find out why is your case not working, here is how I did when I had something similar to do:
get the image sourcce (dom-to-image result)
set up a canvas with that image inside (using the image source)
download the image from canvas in whatever image you like: png, jpeg whatever
by the way you can resize the image to a standard format
document.getElementById('mydownload').onclick= function(){
var wrapper = document.getElementById('wrapper');
//dom to image
domtoimage.toSvg(wrapper).then(function (svgDataUrl) {
//download function
downloadPNGFromAnyImageSrc(svgDataUrl);
});
}
function downloadPNGFromAnyImageSrc(src)
{
//recreate the image with src recieved
var img = new Image;
//when image loaded (to know width and height)
img.onload = function(){
//drow image inside a canvas
var canvas = convertImageToCanvas(img);
//get image/png from convas
var pngImage = convertCanvasToImage(canvas);
//download
var anchor = document.createElement('a');
anchor.setAttribute('href', pngImage.src);
anchor.setAttribute('download', 'image.png');
anchor.click();
};
img.src = src;
// 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;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
}
#wrapper{
background: red;
color: blue;
}
<script src="https://rawgit.com/tsayen/dom-to-image/master/src/dom-to-image.js"></script>
<button id='mydownload'>Download DomToImage</button>
<div id="wrapper">
<img src="http://i.imgur.com/6GvKdxY.jpg"/>
<div> DUDE IS WORKING</div>
<img src="http://i.imgur.com/6GvKdxY.jpg"/>
</div>
I translated #SilentTremor's solution into React/JS-Class:
class SVGToPNG {
static convert = function (src) {
var img = new Image();
img.onload = function () {
var canvas = SVGToPNG.#convertImageToCanvas(img);
var pngImage = SVGToPNG.#convertCanvasToImage(canvas);
var anchor = document.createElement("a");
anchor.setAttribute("href", pngImage.src);
anchor.setAttribute("download", "image.png");
anchor.click();
};
img.src = src;
};
static #convertImageToCanvas = function (image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
};
static #convertCanvasToImage = function (canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
};
}
export default SVGToPNG;
Usage:
let dataUrl = someCanvas.toDataURL("image/svg+xml");
SVGToPNG.convert(dataUrl);

html5-canvas: Conversion of Image file to DataURL throws Uncaught TypeError

I'm trying to get the Base64/Data URL of a chosen image file in Javascript. The user basically selects an image via the File Input control and the Data URL is generated. However, I get this error:
Uncaught TypeError: Failed to execute 'drawImage' on
'CanvasRenderingContext2D': The provided value is not of type
'(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or
ImageBitmap)'
HTML:
<body>
<form id="form1">
<div>
<input type="file" id="imageinput" onchange="testit(event)" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>
</div>
</form>
</body>
Javascript:
function testit(event) {
var myImage = URL.createObjectURL(event.target.files[0]);
var myCanvas = document.getElementById('mycanvas');
var ctx = myCanvas.getContext('2d');
ctx.drawImage(myImage, 0, 0);
var mydataURL = myCanvas.toDataURL('image/jpg');
alert(mydataURL);
}
Why isn't this code working, guys?
You can not draw an image from url directly to canvas. You have to create a image element/object to do that.
var myCanvas = document.getElementById('mycanvas');
var ctx = myCanvas.getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0);
alert(myCanvas.toDataURL('image/jpeg'));
};
img.src = URL.createObjectURL(event.target.files[0]);
Here we have created a image object and set the src to user selected image url. After the image is loaded we are adding it to the canvas.
EDIT:
Here we have one more problem. Whatever the image size is, you will always get 300x300 cropped dataurl of the image because of the static canvas width and height. So we can set the width and height to the canvas dynamically after the image loaded. We can use console.log() instead of alert() so that you can open and see the image from your console in your browser itself.
myCanvas.width = img.width;
myCanvas.height = img.height;
Here is the final code:
var myCanvas = document.getElementById('mycanvas');
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);
console.log(myCanvas.toDataURL('image/jpeg'));
};
img.src = URL.createObjectURL(event.target.files[0]);
Here is the fiddle (i have made the canvas visible so that you can see the whole image and width and height change in canvas):
UPDATE:
As #Kaiido mentioned, It will produce PNG image since the 'image/jpg' is not the mimetype. 'image/jpeg' is the mimetype for both JPG and JPEG images.
Updated Fiddle:
http://jsfiddle.net/k7moorthi/r8soo95p/4/
You're trying to draw an object URL to the canvas. you need to create an image in memory first
http://jsfiddle.net/zmtu6t6c/4/
var myImageUrl = URL.createObjectURL(event.target.files[0]);
var myImage = new Image();
myImage.src = myImageUrl;
myImage.onload = function(){
... then do the canvas stuff
}

Canvas - DrawImage Method

I got a strange problem with the "DrawImage"-Methode of the Canvas element. With the following code I create the canvas and attache it to the "rightcanvas" div.
var rightcanvas = document.getElementById('rightcanvas');
rcanvas = document.createElement('canvas');
rcanvas.setAttribute('width', canvasLength);
rcanvas.setAttribute('height', canvasHeight);
rcanvas.setAttribute('id', 'rcanvas');
rightcanvas.appendChild(rcanvas);
And now I try to draw a Base64 encoded image.
var rcontext = rcanvas.getContext('2d');
var image = new Image();
image.src = 'data:image/png;base64,iVBOR....';
rcontext.drawImage(image,0,0);
The canvas will be created and attached. But the image will not be displayed.Does somebody know what the problem is? =(
You have to wait for the image to load before drawing it to the canvas.
var image = new Image();
image.onload = function() {
rcontext.drawImage(image, 0, 0);
}
image.src = 'data:image/png;base64,iVBOR....';

Categories

Resources