简体   繁体   English

无法使用AJAX / PHP将图像画布保存到文件

[英]Unable to save image canvas to file using AJAX/PHP

I found a great image cropper tool to use for my application. 我发现了一个很棒的图像裁剪工具可用于我的应用程序。 http://tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas/ http://tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas/

Works perfect, crops just like I want, but I can't figure out how to save the cropped file via PHP/AJAX. 完美运行,就像我想要的那样裁剪,但是我不知道如何通过PHP / AJAX保存裁剪的文件。 While there are many files involved, the 3 to modify are: 虽然涉及许多文件,但要修改的3个文件是:

index.php (Cropper Tool)
savefile.php
js/component.js  (the main functions)

In the comments of the above linked article, someone altered the JS to send an AJAX call to a PHP file to 'save' the cropped image. 在以上链接文章的评论中,有人更改了JS以将AJAX调用发送到PHP文件以“保存”裁剪后的图像。 I can't get it to work. 我无法正常工作。

Here's the code and my modifications to component.js 这是代码和我对component.js的修改

crop = function(){
//Find the part of the image that is inside the crop box
var crop_canvas,
    left = $('.overlay').offset().left - $container.offset().left,
    top =  $('.overlay').offset().top - $container.offset().top,
    width = $('.overlay').width(),
    height = $('.overlay').height();

crop_canvas = document.createElement('canvas');
crop_canvas.width = width;
crop_canvas.height = height;

crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);

//=== set our canvas data 
var canvasData = crop_canvas.toDataURL('image/png');

//=== call ajax to fire php save function
var ajax = new XMLHttpRequest();    
ajax.open('POST','savefile.php',true);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);


//=== displays image in new window to prove its working
window.open(crop_canvas.toDataURL('image/png'));

}

The next part is the savefile.php. 下一部分是savefile.php。 I can never tell if this is actually firing or not since nothing is saved. 由于无法保存任何内容,因此我永远无法确定这实际上是在触发。

<?php

$imageData = $_POST['data'];

//==== replace with dynamic names later ===
$imgFile = “test.jpg”;

if (!empty($imageData)) {
  // Remove the headers (data:,) part.
  // A real application should use them according to needs such as to check image type
  $filteredData=substr($imageData, strpos($imageData, “,”)+1);

  // Need to decode before saving since the data we received is already base64 encoded
  $unencodedData=base64_decode($filteredData);

  // Save file.
  $fp = fopen( '$imgFile', ‘wb’ );
  fwrite( $fp, $unencodedData);
  fclose( $fp );
}
header (‘Location: index.php’);
?>

Insight is greatly appreciated - spent all Friday night trying to debug to no avail! 非常感谢您的洞察力-整个星期五晚上都在尝试调试无济于事!

You may require only few changes, still I am posting both ajax and php codes. 您可能只需要进行少量更改,但我仍在发布ajax和php代码。 Here, I am not looking towards the canvas and dataURL, and I consider canvasData as dataURL. 在这里,我不希望使用canvas和dataURL,而是将canvasData视为dataURL。

Here is ajax, first select xmlhttp method as per browser, open ajax query, add request header, and send data. 这是ajax,首先根据浏览器选择xmlhttp方法,打开ajax查询,添加请求标头,然后发送数据。

if (window.XMLHttpRequest) 
          {  xmlhttp = new XMLHttpRequest();
        } else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {             
              functions(xmlhttp.responseText);} }
        xmlhttp.open("POST","test1.php",true);
        xmlhttp.setRequestHeader('Content-Type', 'application/upload');
        xmlhttp.send(canvasData);

In php, the post of data will be coming as "HTTP_RAW_POST_DATA". 在php中,数据的发布将以“ HTTP_RAW_POST_DATA”的形式出现。 So the PHP will be as follows. 因此,PHP将如下所示。

if(isset($GLOBALS["HTTP_RAW_POST_DATA"]))  //if data send
{
$imgFile = 'test.jpg';   //set file name to write
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];   //copy data from globals to variable
$filteredData=substr($imageData, strpos($imageData, ",")+1); //filter dataurl string
$unencodedData=base64_decode($filteredData);   //decode url
$fp = fopen( $imgFile, 'wb' );    //open file with write permission
fwrite( $fp, $unencodedData);     //write file
fclose( $fp );   //close the filehandling
}

Your $imageData variable gets empty $_POST['data'] (I guess). 您的$imageData变量为空$_POST['data'] (我想)。 Try using FormData : 尝试使用FormData

var ajax = new XMLHttpRequest();    
ajax.open('POST','savefile.php',true);
var data = new FormData();
data.append('data', canvasData);
ajax.send(data);

or as You are already using jQuery: 或者因为您已经在使用jQuery:

$.post('saveimage.php', {data: canvasData}, function(){
    alert('Image saved!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM