简体   繁体   English

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

[英]How to rotate image and resize with transparent background using PHP GD

Following code using for rotate an image and resize the same, 以下代码用于旋转图像并调整其大小,

<?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) ;

?>

But its not getting transparent background for output image. 但是它并没有为输出图像提供透明的背景。 How to keep the transparent background. 如何保持透明背景。

Any help please 任何帮助请

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

usage: 用法:

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

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

I think you need to use the imagecolortransparent() function. 我认为您需要使用imagecolortransparent()函数。

Documentation 文档

change : 变化:

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

to : 至 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM