I am having a problem working with images and php.
I am using a function with which will resize an image according to my limitations and then create a new image.
The problem is when I have a png or gif file to resize, the transparency gets lost generating images with black background.
Here is the function:
// Resize image - preserve ratio of width and height.
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 70)
{
// Obtain image from given source file.
$info = getimagesize($sourceImage);
$imgtype = image_type_to_mime_type($info[2]);
switch ($imgtype) {
case 'image/jpeg':
$image = imagecreatefromjpeg($sourceImage);
break;
case 'image/png':
$image = imagecreatefrompng($sourceImage);
break;
default:
die('Invalid image type.');
}
// Get dimensions of source image.
list($origWidth, $origHeight) = getimagesize($sourceImage);
if ($maxWidth == 0)
{
$maxWidth = $origWidth;
}
if ($maxHeight == 0)
{
$maxHeight = $origHeight;
}
// Calculate ratio of desired maximum sizes and original sizes.
$widthRatio = $maxWidth / $origWidth;
$heightRatio = $maxHeight / $origHeight;
// Ratio used for calculating new image dimensions.
$ratio = min($widthRatio, $heightRatio);
// Calculate new image dimensions.
$newWidth = (int)$origWidth * $ratio;
$newHeight = (int)$origHeight * $ratio;
// Create final image with new dimensions.
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
imagejpeg($newImage, $targetImage, $quality);
// Free up the memory.
imagedestroy($image);
imagedestroy($newImage);
return true;
}