I have one functionality on my website where I want to convert svg into png and allow user to download that png image into their local machine.
I have achieved this using the below code.
var btn = document.querySelector('#download');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');
console.log(jQuery.browser);
btn.addEventListener('click', function () {
var data = (new XMLSerializer()).serializeToString(svg);
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svgBlob = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
alert("after load");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//set the image quality
ctx.webkitImageSmoothingEnabled = true;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
// convert to png code
if (canvas.msToBlob)
{ //for IE
ctx.drawImage(img, 0, 0, 1226, 1066);
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, 'shnooks.png');
}
else
{
//other browsers
var imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
if(jQuery.browser.safari)
{
saveImageInSafari(imgURI);
}
else
{
triggerDownload(imgURI);
}
}
};
img.src = url;
});
function triggerDownload (imgURI) {
var evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
});
var a = document.createElement('a');
a.setAttribute('download', 'shnooks.png');
a.setAttribute('href', imgURI);
a.setAttribute('target', '_blank');
a.dispatchEvent(evt);
}
function saveImageInSafari(imgURI)
{
// download file using php
jQuery.post("save.php", {data: imgURI}, function (file) {
window.location.href = "download.php?path=" + file;
});
}
I have also written code in PHP for Safari to download image and it works too.
The only problem I am facing is for the iPhone. img.onload
method is not working on the iPhone.
This code is working and download png on every other browser and android phone, even in the iPad.