Save Canvas image on Ipad - javascript

The webpage is being run on Safari on an iPad.
I have a canvas with the id "canvas1div". I would like to be able to receive this canvas as an image either by email or directly into the photo library.
Via Photo Library
With regards to the photo library, I found this question
Save canvas image on local mobile storage for IOS/Android
This is the function that I would like to call to save the image
function saveimage() {
window.canvas2ImagePlugin.saveImageDataToLibrary(
document.getElementById('canvas1div')
);
}
I don't know how to manually add the plug in to javascript so any advice here would be greatly appreciated.
Email
Again I don't know how to convert the canvas to an image and email it.
Thank you for your help

Don't know if this helps you but here you can find download but email send from JavaScript with email cannot be done:
Example with download file below http://jsfiddle.net/oa2s5eu7/1/
Javscript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
// 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;
}
document.getElementById('mydownload').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
var anchor = document.createElement('a');
console.log(anchor);
anchor.setAttribute('href', image.src);
anchor.setAttribute('download', 'image.png');
anchor.click();
}
document.getElementById('sendEmail').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
window.open('mailto:test#example.com?subject=subject&body=you cann send only txt from javscript in email ', '_blank');
}
Html:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<button id='mydownload'>Download Image</button>
<button id='sendEmail'>Send Email</button>

Related

How to convert dataurl back to image and display on canvas

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.

How to convert canvas image to standard img? [duplicate]

Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:
<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
<td>
<canvas id="transform_image"></canvas>
</td>
</tr>
<tr>
<td>
<div id="image_for_crop">image from canvas</div>
</td>
</tr>
In JavaScript it should look something like this:
$(document).ready(function() {
img = document.getElementById('picture');
canvas = document.getElementById('transform_image');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
}
transformImg(90);
ShowImg(imgFile);
}
function transformImg(degree) {
if (document.getElementById('transform_image')) {
var Context = canvas.getContext('2d');
var cx = 0, cy = 0;
var picture = $('#picture');
var displayedImg = {
width: picture.width(),
height: picture.height()
};
var cw = displayedImg.width, ch = displayedImg.height
Context.rotate(degree * Math.PI / 180);
Context.drawImage(img, cx, cy, cw, ch);
}
}
function showImg(imgFile) {
if (!imgFile.type.match(/image.*/))
return;
var img = document.createElement("img"); // creat img object
img.id = "pic"; //I need set some id
img.src = imgFile; // my picture representing by src
document.getElementById('image_for_crop').appendChild(img); //my image for crop
}
How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)
canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

jQuery, captured Image download

I'm using an ip camera.
For live stream:
<img id="ip-camera-frame" src="http://192.168.1.10/GetData.cgi?CH=1"></img>
I take a snapshot from camera with link "/GetImage.cgi?CH=0" and i can set "img" tag in modalbox.
This snapshot is OK, I want to download captured image but all download methots getting an new capture and download.
<div id="snapshot" class="modal-demo">
<div class="custom-modal-text">
<img id="snapshot-frame" width="100%"></img >
</div>
<div class="modal-footer">
<button type="button" id="save-snapshot">Download Snapshot</button>
</div>
You can try to copy image data from already loaded and displayed image.
as it describe here:
Get image data in JavaScript?
and download it like it described here:
Browser/HTML Force download of image from src="data:image/jpeg;base64..."
so you should have something like:
document.getElementById('save-snapshot').addEventListener("click", function(e) {
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);
// guess the original format, maybe "image/jpg"
var dataURL = canvas.toDataURL("image/png");
window.open(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = document.getElementById("ip-camera-frame").src;
}, false);

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
}

Categories

Resources