如何使用PHP裁剪图像png透明?

时间:2015-01-05 07:37:55

标签: php gd

我希望使用php裁剪png图像,但仍保持透明。

我目前的代码:

<?php
// usual header used on my all pages
ob_start("ob_gzhandler");
$PHP_SELF=$_SERVER['PHP_SELF'];
// actual script begins here
$type=false;
function open_image ($file) {
    //detect type and process accordinally
    global $type;
    $size=getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
        break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
      break;
      case "image/png":
          $im = imagecreatefrompng($file); //png file
      break;
    default: 
        $im=false;
    break;
    }
    return $im;
}

$url = $_GET['src'];

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($url))) {
  // send the last mod time of the file back
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($url)).' GMT', true, 304); //is it cached?
} else {
$image = open_image($url);
if ($image === false) { die ('Unable to open image'); }

    $thumb_width = $_GET['w'];
    $thumb_height = $_GET['h'];
    $width = imagesx($image);
    $height = imagesy($image);
    $original_aspect = $width / $height;
    $thumb_aspect = $thumb_width / $thumb_height;
    if ( $original_aspect >= $thumb_aspect )
    {
       // If image is wider than thumbnail (in aspect ratio sense)
       $new_height = $thumb_height;
       $new_width = $width / ($height / $thumb_height);
    }
    else
    {
       // If the thumbnail is wider than the image
       $new_width = $thumb_width;
       $new_height = $height / ($width / $thumb_width);
    }
    $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
    // Resize and crop
    imagecopyresampled($thumb,
                       $image,
                       0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                       0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                       0, 0,
                       $new_width, $new_height,
                       $width, $height);


    $im2 = imagejpeg($thumb, NULL, 100); 
    imagecopyResampled ($im2, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);

    header('Content-type: image/jpeg');
    $name=explode(".", basename($_GET['url']));
    header("Content-Disposition: inline; filename=".$name[0]."_t.jpg");
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
    header("Cache-Control: public");
    header("Pragma: public");
    imagejpeg($im2, NULL, 100);
    imagedestroy($im2); 
    imagedestroy($image);
}
?>

但是,如果输入是透明的png图像,缩略图将具有黑色背景,如何保持透明背景?

1 个答案:

答案 0 :(得分:2)

最简单的方法是在图片资源上enable alpha-channel transparency

$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);

您还需要将返回的图像类型更改为PNG(imagepng)而不是JPEG。