【问题标题】:How do i get image using jquery ajax?如何使用 jquery ajax 获取图像?
【发布时间】:2012-06-13 03:52:00
【问题描述】:

我正在使用 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 响应中获得裁剪图像。我在这方面做错了什么?

【问题讨论】:

    标签: php jquery ajax jcrop


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 2016-03-31
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多