Aadi
Aadi

Reputation: 7109

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

Upvotes: 0

Views: 2482

Answers (3)

litopj
litopj

Reputation: 106

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

Upvotes: 1

gmoz22
gmoz22

Reputation: 1346

change :

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

to :

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

Upvotes: 0

b3n
b3n

Reputation: 1324

I think you need to use the imagecolortransparent() function.

Documentation

Upvotes: 0

Related Questions