Welcome to WebmasterWorld Guest from 54.162.93.137

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Why Does imagepng Output a Blank Image?

Resizing a PNG image

     
8:46 pm on May 25, 2012 (gmt 0)

5+ Year Member Top Contributors Of The Month



Hi,

Here's a script that resizes a PNG image. At the end it creates the resized thumb.png but it is blank... i.e. white. I've been through the PHP manual and as far as I understand it, everything makes sense. It would be interesting to understand at which point does this script lose the original data. Thanks!

<?php
$url = "path/to/large/image.png";
$image = imagecreatefrompng($url);

$result = imagecreate(148,111);
$fg = imagecolorallocate($result,255,255,255);
imagefilledrectangle($result,0,0,148,111,$fg);
$w = imagesx($image);
$h = imagesy($image);

$wscale = 148 / $w;
$hscale = 111 / $h;

if ($wscale < $hscale) {
$xresult = 148;
$yresult = $h * $wscale;
$xoffset = 0;
$yoffset = (111 - $yresult)/2;
} else {
$yresult = 111;
$xresult = $w * $hscale;
$xoffset = (148 - $xresult) / 2;
$yoffset = 0;
}

ImageCopyresized($result,$image,$xoffset,$yoffset,0,0,$xresult,$yresult,$w,$h);
imagepng($result, "thumb.png");
imagedestroy($result);
?>
11:12 pm on Jun 1, 2012 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



It is likely in your scaling ...

$w = imagesx($image);
$h = imagesy($image);
$wscale = 148 / $w;
$hscale = 111 / $h;


Try running it through a proportional resizing routine, something like ...

/**
* Resizes images proportionally for display format
*
* @param string $image path to image
* @param integer $maxImgWidth maximum image width for display
* @return array
*/
function resizeProportionally($image, $maxImgWidth = 100)
{
$w = $maxImgWidth;
$h = $maxImgWidth;
if ($list = @getimagesize($image)) {
list($w, $h, $t, $a) = $list;
if ($w > $maxImgWidth) {
$h = $h*($maxImgWidth/$w);
$w = $maxImgWidth;
}
}
return array($w, $h);
}
list($iw, $ih) = resizeProportionally($image, 111);
8:44 am on Jul 4, 2012 (gmt 0)

5+ Year Member Top Contributors Of The Month



Thanks for the idea.
You know what it was in the end? A faulty path :D
10:47 am on Jul 5, 2012 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Glad you got it sorted. My simple function there should be checking for height too. If you decided to use it you may want to check the height right after the width so you would add another "if" conditional after the width conditional ...

if ($h > $maxImgWidth) {
$w = floor($w*($maxImgWidth/$h));
$h = $maxImgWidth;
}
 

Featured Threads

Hot Threads This Week

Hot Threads This Month