Saving canvas as a PNG or JPG

后端 未结 3 1953
无人共我
无人共我 2021-02-01 20:09

I want to save canvas as PNG, without opening it in a new window as base64-encoded image.

I used this code:

jQuery(\"#btnPreview\").click(function(){
            


        
相关标签:
3条回答
  • 2021-02-01 20:44

    In script.js file

      $(document).on('click','#btnPreview',function(){
         var img =$scope.canvas.toDataURL('image/png');
         $.ajax({
                    type: "POST",   
                    url: 'ajax.php', 
                    data: {'img':img},
                    success: function(data) { 
                        $("#loader_message").html("Image saved successfully"); 
                    }
                });
      });
    

    In ajax.php

        $encodedData=explode(',', $_POST["img"]);
        $data = base64_decode($encodedData[1]);
        $urlUploadImages = $_SERVER['DOCUMENT_ROOT'].$projName.'/images/canvas/';
        $nameImage = "test.png";
        $img = imagecreatefromstring($data);
         if($img) {
            imagepng($img, $urlUploadImages.$nameImage, 0);
            imagedestroy($img); 
            echo "OK";
        }
        else {
            echo 'ERROR';
        }
    
    0 讨论(0)
  • 2021-02-01 20:46

    canvas.toDataURL('png') provides a string a la data:image/png;base64,XYZ. You could stuff that into an <a href="%dataURI%" download>download</a> (possibly trigger a click event on the element). See Downloading resources in HTML5: a[download]

    Currently supported only by Google Chrome, though.

    0 讨论(0)
  • 2021-02-01 20:56

    I use this on my jquery:

    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
    
    $('.save').attr({
        'download': 'YourProduct.png',  /// set filename
        'href'    : image              /// set data-uri
    });
    
    0 讨论(0)
提交回复
热议问题