Hi there,
I have a system where a user can upload an image, once an image has been uploaded php crops the image and then resizes to to a thumbnail. This works perfectly well with JPEGs, but does not work with PNGs and GIFs.
I have used code to make sure the functions can deal with PNGs and GIFs but then the code runs all that is returned is an empty png or gif file and I do not know why. Here are my functions:
Function to solely resize the image:
function createthumb($name, $filename, $new_w, $new_h)
{
$system = explode(".", $name);
if (preg_match("/jpg|jpeg/", $system[1]))
{
$src_img=imagecreatefromjpeg($name);
}
if (preg_match("/png/", $system[1]))
{
$src_img = imagecreatefrompng($name);
}
if (preg_match("/gif/", $system[1]))
{
$src_img = imagecreatefromgif($name);
}
$old_x = imagesx($src_img);
$old_y = imagesy($src_img);
$thumb_w = $new_w;
$thumb_h = $new_h;
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
if (preg_match("/png/", $system[1]))
{
imagepng($dst_img, $filename, 100);
}
else if (preg_match("/gif/", $system[1]))
{
imagegif($dst_img, $filename, 100);
}
else
{
imagejpeg($dst_img, $filename, 100);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
code to crop the image:
function createthumbcrop($name, $filename, $new_w, $new_h)
{
$system = explode(".", $name);
if (preg_match("/jpg|jpeg/", $system[1]))
{
$src_img=imagecreatefromjpeg($name);
}
if (preg_match("/png/", $system[1]))
{
$src_img = imagecreatefrompng($name);
}
if (preg_match("/gif/", $system[1]))
{
$src_img = imagecreatefromgif($name);
}
$old_x = imagesx($src_img);
$old_y = imagesy($src_img);
if ($old_x > $old_y)
{
$width = ($old_x - $old_y) / 2;
$height = 0;
}
else if ($old_y > $old_x)
{
$width = 0;
$height = ($old_y - $old_x) / 2;
}
else
{
$width = 0;
$height = 0;
}
// New image size
$thumb_w = $new_w;
$thumb_h = $new_h;
// Starting point of crop
$tlx = floor($old_x / 2) - floor($thumb_w / 2);
$tly = floor($old_y / 2) - floor($thumb_h / 2);
// Adjust crop size if the image is too small
if ($tlx < 0)
{
$tlx = 0;
}
if ($tly < 0)
{
$tly = 0;
}
if (($old_x - $tlx) < $thumb_w)
{
$thumb_w = $old_x - $tlx;
}
if (($old_y - $tly) < $thumb_h)
{
$thumb_h = $old_y - $tly;
}
if ($old_x > $old_y)
{
$dst_img = imagecreatetruecolor($old_y, $old_y);
}
else if ($old_y > $old_x)
{
$dst_img = imagecreatetruecolor($old_x, $old_x);
}
else
{
$dst_img = imagecreatetruecolor($old_x, $old_y);
}
imagecopy($dst_img, $src_img, 0, 0, $width, $height, $old_x, $old_y);
/*
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
*/
if (preg_match("/png/", $system[1]))
{
imagepng($dst_img, $filename, 100);
}
else if (preg_match("/gif/", $system[1]))
{
imagegif($dst_img, $filename, 100);
}
else
{
imagejpeg($dst_img, $filename, 100);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
I hope someone can help.
Thanks.