如何使用php和ajax将Canvas元素保存到png文件?

时间:2013-12-19 12:51:12

标签: javascript php jquery ajax canvas

我想使用php和jquery ajax将html canvas元素保存为图像。 这是我的ajax代码。

   var  front_image=canvas.toDataURL("image/png");
//front image is a base_64 string
                 $.ajax({
                  url:base_url+'tabs/profile/save_front_image',
                  type:'POST',
                  data:'front_image='+front_image,
                  success:function(response){


                  }
              });

我只是在php echo中执行echo $_POST['front_image']所以请求和响应是一样的。

当我在ajax之前使用此代码时,它会将图像加载到浏览器的新选项卡

 var w = window.open('about:blank', 'image from canvas');
   w.document.write("<img src='" + frame_image + "' alt='from canvas'/>");

但是当我把相同的代码放在ajax响应上时,它不起作用。浏览器中只打开一个空白选项卡。所以我无法将图像保存为文件。

var w = window.open('about:blank', 'image from canvas');
 w.document.write("<img src='" + response + "' alt='from canvas'/>");

我还比较了frame_imageresponse的字符串长度。他们是一样的。我不确定为什么图像没有加载响应。请给我答案谢谢。

1 个答案:

答案 0 :(得分:3)

// soon you can use front_image=canvas.toBlob("image/png")

// construct a blob
function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

// make an actually file from the base64 so we can send binary data
var blob = b64toBlob(front_image.split(",")[1], "image/png")
var fd = new FormData();

fd.append("file", blob, "filename.png");

$.ajax({
    url: 'http://example.com/script.php',
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

//保存

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["file"]["tmp_name"][$key];
        $name = $_FILES["file"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>