Rodrigo
Rodrigo

Reputation: 5119

How to crop an image in PHP and return as PNG?

I want to crop a world map on the server with PHP, according to given coordinates, and return the cropped image to be added to a web page through AJAX. I don't want to save the resulting image on the server.

My PHP code.

<?php
if (isset($_GET['lon0']) && isset($_GET['lon1']) && isset($_GET['lat0']) && isset($_GET['lat1'])) {
    $lon0 = $_GET['lon0'];
    $lon1 = $_GET['lon1'];
    $lat0 = $_GET['lat0'];
    $lat1 = $_GET['lat1'];
} else {
    return 1;
}
if (isset($_GET['w'])) {
    $which = 'raster/W'.$_GET['w'].'.png';
    $img = imagecreatefrompng($which);
    if ($img) {
        $W = imagesx($img);
        $H = imagesy($img);
        $x = ($lon0+180)*$W/360;
        $y = (90-$lat1)*$H/150;
        $w = ($lon1-$lon0)*$W/360;
        $h = ($lat1-$lat0)*$H/150;
        $arr = array('x'=>$x,'y'=>$y,'width'=>$w,'height'=>$h);
        $imgCrop = imagecrop($img,$arr);
        if ($imgCrop) {
            header('Content-Type: image/png');
            fpassthru($imgCrop);
        }
    }
}

I'm getting the following error.

PHP error message

Modifying the code to understand what's happening:

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if (isset($_GET['lon0']) && isset($_GET['lon1']) && isset($_GET['lat0']) && isset($_GET['lat1'])) {
    $lon0 = $_GET['lon0'];
    $lon1 = $_GET['lon1'];
    $lat0 = $_GET['lat0'];
    $lat1 = $_GET['lat1'];
} else {
    return 1;
}
if (isset($_GET['w'])) {
    $which = 'raster/W'.$_GET['w'].'.png';
    $img = imagecreatefrompng($which);
    if ($img) {
        $W = imagesx($img);
        $H = imagesy($img);
        echo "$W x $H<br>\n";
        $x = ($lon0+180)*$W/360;
        $y = (90-$lat1)*$H/150;
        $w = ($lon1-$lon0)*$W/360;
        $h = ($lat1-$lat0)*$H/150;
        $arr = array('x'=>$x,'y'=>$y,'width'=>$w,'height'=>$h);
        $imgCrop = imagecrop($img,$arr);
        echo is_resource($imgCrop) ? 'is resource' : 'is not';
        if ($imgCrop) {
            fpassthru($imgCrop);
        }
    }
}

I get the following output.

10800 x 4500
is resource
Warning: fpassthru(): supplied resource is not a valid stream resource in /var/www/html/sn/getImg.php on line 31

Which means the original file was read successfully, and the image was cropped. So why is fpassthru complaining that the resource is invalid?

Upvotes: 0

Views: 164

Answers (1)

FAEWZX
FAEWZX

Reputation: 1029

Try using the image* functions.

if ($imgCrop) {
header('Content-Type: image/png');
imagepng($imgCrop);
imagedestroy($imgCrop);
}
imagedestroy($img);
exit();

Upvotes: 3

Related Questions