How do i get image using jquery ajax?
Asked Answered
H

1

5

I am using jcrop to crop the image in my php application.I am using below code to pass the coordinate values and image path using 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.');
            }

In Controller, I use the ajax value as below,

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

I got the response as something like

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

Instead of cropped image, got some symbol. Need to get cropped image in ajax response. What i done wrong on this ?

Halsted answered 9/6, 2012 at 9:23 Comment(0)
T
8

You are sending the full image data back as response, instead save the image on the server and send the URL to it as a response

instead

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

have this

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

Also, your success function should look like

success : function(url) { 
    jQuery(".preview_crop").html('<img src="' + url + '" />');
}
Tetrahedron answered 9/6, 2012 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.