如何使用jQuery AJAX获取图片?

5

我正在使用jcrop在我的php应用程序中裁剪图片。我正在使用以下代码通过ajax传递坐标值和图像路径:

function checkCoords(index)
    {
            if (parseInt(jQuery('#w').val())){
                    jQuery.ajax({
                        type    : "POST",
                        cache: false,
                        dataType: 'html',
                        data    : {
                                x : jQuery('#x').val(),
                                y : jQuery('#y').val(),
                                w : jQuery('#w').val(),
                                h : jQuery('#h').val(),
                       image_path : jQuery('#jc-hidden-image'+index).attr('src')
                        },
                        url     : BASE_URL+'apps/configure/cropimage',
                        success : function(response) { 
                                jQuery(".preview_crop").html(response);
                        }
                    });                     
            } 
            else{
                alert('Please select a crop region then press Crop button.');
            }

在控制器中,我使用ajax的值如下所示:

  public function cropimageAction(){
        $params = $this->getRequest()->getParams();
        //d($params);
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        {
                $targ_w = $targ_h = 150;
                $jpeg_quality = 90;

                $src = $params['image_path'];
                $img_r = imagecreatefromjpeg($src);
                $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

                $image  = imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);

               header('Content-type: image/jpeg');
                imagejpeg($dst_r,null,$jpeg_quality);

                exit;
        }        
    }

我得到的响应是像下面这样的东西

��(��(��(��(��

在Ajax响应中,没有得到裁剪后的图片,而是一些符号。我在这方面做错了什么?
1个回答

8
您正在将完整的图像数据作为响应发送,而不是将其保存在服务器上并将URL作为响应发送。
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);

拥有这个

imagejpeg($dst_r,"path/where/to/save/image.jpg",$jpeg_quality);
echo "path/where/to/save/image.jpg";

此外,您的成功函数应该长这样:

success : function(url) { 
    jQuery(".preview_crop").html('<img src="' + url + '" />');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接