繁体   English   中英

如何使用jquery ajax获取图像?

[英]How do i get image using jquery ajax?

我正在使用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.'); } 

在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;
        }        
    }

我得到了回应

((((

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

您将完整图像数据作为响应发送回来,而是将图像保存在服务器上并将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 + '" />');
}

暂无
暂无

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

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