如何使用jquery ajax获取图像?

mym*_*and 5 php ajax jquery jcrop

我正在使用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.');
            }
Run Code Online (Sandbox Code Playgroud)

在Controller中,我使用如下的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;
        }        
    }
Run Code Online (Sandbox Code Playgroud)

我得到了回应

((((

而不是裁剪图像,得到了一些符号.需要在ajax响应中获取裁剪图像.我做错了什么?

sla*_*197 8

您将完整图像数据作为响应发送回来,而是将图像保存在服务器上并将URL作为响应发送给它

代替

header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
Run Code Online (Sandbox Code Playgroud)

拥有这个

imagejpeg($dst_r,"path/where/to/save/image.jpg",$jpeg_quality);
echo "path/where/to/save/image.jpg";
Run Code Online (Sandbox Code Playgroud)

此外,您的成功功能应该是这样的

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