如何使用PHP GD旋转图像并使用透明背景调整大小

时间:2011-09-28 08:16:35

标签: php background gd transparent

以下代码用于旋转图像并调整其大小,

<?php

$src = "41611326.png";

// Get new dimensions
list($width, $height) = getimagesize($src);

$new_width = 192;
$new_height = 192;
$dstimage=imagecreatetruecolor($new_width,$new_height);

$srcimage = imagecreatefrompng($src);

$degrees = -30;

$srcimage = imagerotate($srcimage, $degrees, 0) ;

imagealphablending($dstimage, false);
imagesavealpha($dstimage, true);

imagecopyresampled($dstimage,$srcimage,0,0,0,0, $new_width,$new_height,$width,$height);

header('Content-type: image/png') ;
imagepng($dstimage) ;

?>

但它没有获得输出图像的透明背景。如何保持透明背景。

请帮助

3 个答案:

答案 0 :(得分:1)

function rotate_transparent_img( $img_resource, $angle ){

    $pngTransparency = imagecolorallocatealpha( $img_resource , 0, 0, 0, 127 );
    imagefill( $img_resource , 0, 0, $pngTransparency );

    $result = imagerotate( $img_resource, $angle, $pngTransparency );
    imagealphablending( $result, true );
    imagesavealpha( $result, true );

    return $result;
}

<强>用法:

$img_resource = imagecreatefrompng('transparent_img.png');
$angle = 30;

$res = rotate_transparent_img( $img_resource, $angle );
header('Content-Type: image/png');
imagepng($res);

答案 1 :(得分:0)

我认为你需要使用imagecolortransparent()函数。

Documentation

答案 2 :(得分:0)

改变:

$srcimage = imagerotate($srcimage, $degrees, 0) ;

到:

$srcimage = imagerotate($srcimage, $degrees, -1);