2

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Ankur Vyas
  • 118
  • 9

1 Answers1

0

It's a way old question, I don't get what do you mean by: (img.onload method is not working on the iPhone.). In general I see that you need to replace the type of blob to image/png, also there is no need to differentiate between browsers now since most browsers support the Blob generation and downloading as png image without any problems. Also no need to replace('image/png', 'image/octet-stream') just keep it as it is and pass it to the image src. Hope this can help somebody.

Yaser AZ
  • 384
  • 1
  • 5