如何在浏览器中将SVG转换为图像(JPEG,PNG等)并将其保存在服务器上以进行产品预览以结帐

时间:2019-05-14 10:33:05

标签: javascript svg

我正在使用html2canvas转换svg,以便在使用base64结帐之前在服务器端另存为png产品预览。 svg工作正常。用于自定义商品结帐。问题是自定义和单击签出后,svg图像在签出之前不会保存到签出页面上进行预览。原因是我不写什么来保存它的PHP。我需要编写“ savetoserver.php”的php代码以保存到服务器的帮助

function imagetopng(){
      function showCheckout() {
        $("#checkoutcontainer").show();
        $(".productoverview").show();
        $("#popup").show();


      }
      setTimeout(showCheckout, 500);
      html2canvas($(".stole"), {
          allowTaint: true,
          letterRendering: true,
          onrendered: function(canvas) {
          $('.stole-png').prepend(canvas);
            var dataURL = canvas.toDataURL('image/png', 1.0);
            $.ajax({
              type: "POST",
              url: "savetoserver.php",
              data: {
                 imgBase64: dataURL
              }


            })
            .done(function(o) {

                var fileurl = o;
                var websiteurl = "http://woven.indexsta.com/";
                var formatted = websiteurl + fileurl;
                //var formatted = "stole-designs/" + fileurl
                $('#stole-url').attr('value', formatted);
                $('#stolepreview').attr('src', fileurl);

              // If you want the file to be visible in the browser
              // - please modify the callback in javascript. All you
              // need is to return the url to the file, you just saved
              // and than put the image in your browser.
            });
          }
      });
      $('.stole-png').empty();


    };

    $('#closecheckout').on('click touch',function(){
      $("#checkoutcontainer").css('display','none');
      $("#popup").css('display','none');

    });

1 个答案:

答案 0 :(得分:0)

I figured it out. Incase anyone faces same challenge, here's the script i wrote to solve it. 

<?php  
      // requires php5+ 
       // create directory
      if (!file_exists('images/')) {
        mkdir('images/', 0777, true);
      }
      define('UPLOAD_DIR', 'images/');  
      $img = $_POST['imgBase64'];  
      $img = str_replace('data:image/png;base64,', '', $img);  
      $img = str_replace(' ', '+', $img);  
      $data = base64_decode($img);  
      $file = UPLOAD_DIR . uniqid() . '.png';  
      $success = file_put_contents($file, $data);  
      print $success ? $file : 'Unable to save the file.';  
 ?>