Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize PNG image in PHP

Tags:

php

png

resize

gd

I'm getting a no image display when resizing PNG however the following code works for JPEG.

list($width_orig, $height_orig) = getimagesize( $fileName );

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);

if( $type )){
    switch( $type ){
        case 'image/jpeg':
            $image = imagecreatefromjpeg($fileName);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            imagejpeg($image_p, null, 100);
        break;

        case 'image/png':
            imagealphablending( $image_p, false );
            imagesavealpha( $image_p, true );
            $image = imagecreatefrompng( $fileName );
            imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            imagepng($image_p, null, 100);
        break;
    }
}

I've put the headers in but for some reason I'm doing something wrong for png images.

like image 542
Ian Avatar asked Feb 21 '11 10:02

Ian


People also ask

How do I scale an image in PHP?

The imagescale() function is an inbuilt function in PHP which is used to scale an image using the given new width and height. Parameters: This function accepts four parameters as mentioned above and described below: $image: It is returned by one of the image creation functions, such as imagecreatetruecolor().


1 Answers

try this:

$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;

// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
like image 72
Alex Pliutau Avatar answered Oct 08 '22 10:10

Alex Pliutau