I am creating a thumbnail of myImage
of various format (jpg, png)
. Here is my code
<?php
error_reporting(E_ALL);
//$file = 'H:/xampp/htdocs/myfolder/new.jpg';
$file = 'H:/xampp/htdocs/myfolder/phool.png';
$pathToSave = 'H:/xampp/myfolder/New/';
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);
//print "MIME ".$what['mime'];
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$img = imagecreatefromstring($img);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
imagepng($new,$pathToSave.$file_name);
imagedestroy($new);
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
break;
case 'image/gif':
$img = imagecreatefromgif($file);
break;
default: die();
}
But, It is not working for PNG images.It saves a blank image in my destination $pathToSave = 'H:/xampp/htdocs/myfolder/New/'
.
If I remove $img = imagecreatefromstring($img);
then imagepng
saves the image as it is but does not compress the image as imagejpg
does.
$img = imagecreatefrompng($file); //Creates an image from a png file
$img = imagecreatefromstring($img); //Creates an image from a string
Basicly you are creating an image in memory using imagecreatefrompng($file) but then you overwrite the same variable using imagecreatefromstring($img) which doesn't take a GDImage variable as parameter so it returns a blank image (or null?).
Just remove imagecreatefromstring($img); and it will work.
$newImage = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($fileurl);
imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($newImage,$fileurl);
imagedestroy($newImage);
imagedestroy($source);