Data URI to Object URL with createObjectURL in chrome/ff

后端 未结 3 1368
栀梦
栀梦 2021-01-03 02:55

I have base64 string of an image. How can I convert this to Object URL? The purpose is to try and see if my svg-editor will be faster, by injecting Blob URL to the DOM inste

相关标签:
3条回答
  • 2021-01-03 03:24

    If somebody want to save Data URI as an image in server:

    Pass Data URI to server by post request:

    var imgData = canvas.toDataURL('image/png');
    $.post("https://path-to-your-script/capture.php", {image: imgData},
        function(data) {
            console.log('posted');
    });
    

    Save image: capture.php

    $data = $_POST['image'];
    
    // remove "data:image/png;base64," from image data.
    $data = str_replace("data:image/png;base64,", "", $data);
    
    // save to file
    file_put_contents("/tmp/image.png", base64_decode($data));
    
    0 讨论(0)
  • 2021-01-03 03:35

    Try this code.

    function dataURItoBlob(dataURI) {
      var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
         array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: mime});
    }
    

    and use it like this

    var objecturl = URL.createObjectURL(dataURItoBlob('your data url goes here'));
    
    0 讨论(0)
  • 2021-01-03 03:42

    What happens if you want to show html in an iframe?

    iframe.src = "data:text/html,"+encodeURIComponent( window.btoa(text) );
    
    0 讨论(0)
提交回复
热议问题