Making Thumbnails, but having trouble with PNG - php

I'm creating thumbnails using php, and it is working fine for GIF and JPEG, but not for PNG. When I run this script, with a PNG, a thumbnail doesn't save. Can you show me what I am doing wrong? Thanks in advance!
public function make_thumbs($img_src)
{
//Desired thumbnail width
$width = 100;
//Thumbnail name
$thumb = 'th_' . $img_src;
//Ensure the image exists
if(file_exists($img_src)){
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
//Create image stream
$image = imagecreatefromgif($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
//Create image stream
$image = imagecreatefromjpeg($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
//Create image stream
$image = imagecreatefrompng($img_src);
}
//Gather and store the width and height
list($image_width, $image_height) = getimagesize($img_src);
//Calculate new height while maintaining aspect ratio
$height = (($width / $image_width) * $image_height);
//Resample/resize the image
$tmp_img = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp_img, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//Attempt to save the new thumbnail
if(is_writeable(dirname($thumb)))
{
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
imagegif($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
imagejpeg($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
imagepng($tmp_img, $thumb, 100);
}
}
//clear memory
imagedestroy($tmp_img);
imagedestroy($image);
}
}

Related

Data Loss in JPEG/PNG resizing

I've adapted this code that I found. It resizes .jpg and .png images, and maintains alpha layers.
When I resize an image, however, the reduction in file size is far more than I had anticipated. This isn't a problem for me, as I cannot see with my eyes any degradation or data loss.
What is causing the huge compression of the file, and if I ever needed to, how can I avoid it?
function thumbnail($image, $width, $height, $target) {
if($image[0] != "/") { // Decide where to look for the image if a full path is not given
if(!isset($_SERVER["HTTP_REFERER"])) { // Try to find image if accessed directly from this script in a browser
$image = $_SERVER["DOCUMENT_ROOT"].implode("/", (explode('/', $_SERVER["PHP_SELF"], -1)))."/".$image;
} else {
$image = implode("/", (explode('/', $_SERVER["HTTP_REFERER"], -1)))."/".$image;
}
} else {
$image = $_SERVER["DOCUMENT_ROOT"].$image;
}
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagealphablending($temp_image, false);
imagesavealpha($temp_image,true);
$transparent = imagecolorallocatealpha($temp_image, 255, 255, 255, 127);
imagefilledrectangle($temp_image, 0, 0, $nWidth, $nHeight, $transparent);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//$thumbnail = imagecreatetruecolor($width, $height);
//imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($temp_image, 'img/'.$target.'.jpg');
} else {
imagepng($temp_image,'img/'.$target.'.png');
}
imagedestroy($temp_image);
//imagedestroy($thumbnail);
}
As showdev commented, both imagejpeg() and imagepng() accept a third optional parameter for the image quality. For imagejpeg() it runs from 0 to 100 and defaults to 75), for imagepng() it is from 0 to 9 and defaults to 6.
Also, 4.4Mb is a really big size for a ~2.4Mpx image. It problably contains a lot of metadata and most of it -like Photoshop thumbsnails- is not preserved when you do an imagecopyresampled() with PHP's GD library.
You should also run one of your test images through a lossless compression program like JStrip (http://davidcrowell.com/jstrip/), to check how much it weights without the bloat.

Php Resizing image increase image size

I'm creating thumnails of uploaded file.
if image width and height are greater than 200 than then i re size them to 200px.
Here is code i used to do that:
if (file_exists($old_file)) {
$path_parts = pathinfo($old_file);
$extension = $path_parts['extension'];
$filename_path = $filepath . $filename;
$destination_path = $filename_path;
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
$uploadedfile = $old_file;
$src = imagecreatefromjpeg($uploadedfile);
} else if (strtolower($extension) == "png") {
$uploadedfile = $old_file;
$src = imagecreatefrompng($uploadedfile);
} else {
$uploadedfile = $old_file;
$src = imagecreatefromgif($uploadedfile);
}
list($width, $height) = getimagesize($uploadedfile);
$newwidth = $Size['width'];
$newheight = $Size['height'];
if ($width <= $newwidth && $height <= $newheight) {
$newwidth = $width;
$newheight = $height;
$tmp = imagecreatetruecolor($width, $height);
} else {
if ($width > $height) {
$newheight = ($height / $width) * $newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
} else {
$newwidth = ($width / $height) * $newheight;
$tmp = imagecreatetruecolor($newwidth, $newheight);
}
}
if ((strtolower($extension) == "png") OR (strtolower($extension) == "gif")) {
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
}
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
imagejpeg($tmp, $destination_path, 100);
} elseif (strtolower($extension) == "png") {
imagepng($tmp, $destination_path, 5);
} else {
imagegif($tmp, $destination_path);
}
chmod($destination_path, 0777);
imagedestroy($src);
imagedestroy($tmp);
ob_flush();
flush();
ob_end_flush();
return true;
} else {
return false;
}
it re size the large images to 200px by 200px but image size is increased in (byte and kb etc increased).
I tried uploading 8kb png file, and new thumbnail file size was 28kb?
Tried googling but didn't find anything helpful
Thanks.
Your source image is compressed, after parsing it you get a true color image, which is uncompressed. Then you save it with a compression level of 5 (in the case of PNG), which is pretty low compression, thus a higher filesize.
Try a higher compression, like 9, for example. Also try adding a combination of filters to decrease filesize (http://us3.php.net/manual/en/image.constants.php look for PNG_FILTER_*).
See: http://us3.php.net/manual/en/function.imagepng.php
http://en.wikipedia.org/wiki/Portable_Network_Graphics#Compression
http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_size_factors
The GD library doesn't appear to provide any interfaces to let you in on low-level PNG data, but you can theoretically find out the source compression level and filters, by using other bindings or trying to read it manually.
http://www.libpng.org/pub/png/spec/1.2/PNG-Compression.html
http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
The same may happen with JPG and GIF.

can not crop thumbnail of passed size

I have an image whose size is "300X367" .
I have an image function which crop thumbnail by using this type
but this function crop thumbnail of "41X50". I think it crop thumbnail by scale of original image.
But I want accurate thumbnail size of passing parameter. I can't put code here of image.php as the size is too big.
If anyone have solution for passing size parameter in image tag & crop thumbnail. please tell me.
Try this example code
<?php
function getFileExtenction($image)
{
$imageAry = explode(".", $image);
return $imageAry[1];
}
$image = 'images/imageName.png'; //Your image location
$imageType = getFileExtenction($image); //check the image file type
if ($imageType == "png")
$src = imagecreatefrompng($image);
else if ($imageType == "jpg")
$src = imagecreatefromjpeg($image);
else if ($imageType == "gif")
$src = imagecreatefromgif($image);
else
{
}
list($width, $height) = getimagesize($image); //To get the image width and height
$newwidth = 41; //Give your thumbanail image width
$newheight = 50; //Give your thubnail image height
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename = "NewImagename." . $imageType;
/*========== if you want to store this file in a folder Ex: "thumbs" ==========
$filename = "thumbs/NewImagename." . $imageType;
*/
imagejpeg($tmp, $filename, 100);
imagedestroy($src);
imagedestroy($tmp);
?>

PHP temporary thumbnail

I'm not after saving an image, I just want to scale down an image by percentage and then display it on a webpage
I know I can use getimagesize to get the height width but how to scale correctly?
You can use a function like this .
Refer http://tutorialfeed.net/development/scale-an-image-using-php
function create_thumb( $imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext )
{
//getting the image dimensions
list( $width_orig, $height_orig ) = getimagesize( $imgSrc );
// Check if the images is a gif
if( $ext == 'gif' )
{
$myImage = imagecreatefromgif($imgSrc);
}
// Check if the image is a png
elseif( $ext == 'png' )
{
$myImage = imagecreatefrompng($imgSrc);
}
// Otherwise, file is jpeg
else
{
$myImage = imagecreatefromjpeg($imgSrc);
}
// Find the original ratio
$ratio_orig = $width_orig / $height_orig;
// Check whether to scale initially by height or by width
if( $thumbnail_width / $thumbnail_height > $ratio_orig )
{
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
}
else
{
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width / 2; //horizontal middle
$y_mid = $new_height / 2; //vertical middle
$process = imagecreatetruecolor( round( $new_width ), round( $new_height ) );
// Scale the image down and the reduce the other axis to create the thumbnail
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
// Depending on the file extension, save the file
if( $ext == 'gif' )
{
imagegif( $thumb, $dest_src );
}
elseif( $ext == 'png' )
{
imagepng( $thumb, $dest_src );
}
else
{
imagejpeg( $thumb, $dest_src, 100 );
}
// Remove rubbish file data
imagedestroy($process);
imagedestroy($myImage);
// Return thumb ( success / fail )
return $thumb;
}
You can use the resizeInPourcent() method of ImageWorkshop (a library using the GD library): http://phpimageworkshop.com/doc/17/resizing.html
Ex:
<?php
$myImage->resizeInPourcent(50, 50); // Resize to get 50% width and height

Cropping an image in PHP

I am doing PNG image cropping using this function. Everything is working fine, but whenever I upload the .png, the image background color is changed to black. Here is the code.
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments3";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
} `
even i tried like this also
/************************************Resizing the image 80*60****************/
$path3="partners_logs";
$filetype3=$_FILES["pimage"]["type"];
$bgim_file_name = $path3."/".$Attachments2;
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
imageAlphaBlending($bgim_old, true);
imageSaveAlpha($bgim_old, true);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments2";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
//set the background color to your choice, paramters are int values of red,green and blue
imagecolorallocate($bgim_new,0xFF,0xFF,0xFF);
}
/************End Resize of 80*60*******************/
maybe this helps
Don't forget about
imagealphablending() and
imagesavealpha() if you're working
with [semi]transparent png.
<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
found at php.net - imagecreatefrompng under User Contributed Notes
NOT tested
edit see comment
<?php
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
imageAlphaBlending($bgim_new, true);
imageSaveAlpha($bgim_new, true);
?>
After some testing and reading througt several pnp.net comments i've got a working script
<?php
$newImageName = "PNG_transparency_copy.png";
$newWidth = 265;
$newHeight = 150;
$orgAttribs = getimagesize("PNG_transparency_demonstration_1.png");
$orginal = imagecreatefrompng("PNG_transparency_demonstration_1.png");
imagesavealpha($orginal, true);
$newPng = imagecreatetruecolor($newWidth,$newHeight);
imagealphablending($newPng, false);
$color = imagecolortransparent($newPng, imagecolorallocatealpha($newPng, 0, 0, 0, 127));
imagefill($newPng, 0, 0, $color);
imagesavealpha($newPng, true);
imagecopyresampled($newPng,$orginal,0,0,0,0,$newWidth,$newHeight, $orgAttribs[0], $orgAttribs[1]);
header("Content-type: image/png");
imagepng($newPng,$newImageName);
PNG taken from Wikipedia
Try This Function....
<?php
function CropImg($img_dst, $img_src, $dst_width = 300, $dst_height = 180){
$ext = pathinfo($img_src, PATHINFO_EXTENSION);
if($ext != 'jpg' and $ext != 'jpeg'){
$image = imagecreatefrompng($img_src);
}else{
$image = imagecreatefromjpeg($img_src);
}
$filename = $img_dst;
$thumb_width = $dst_width;
$thumb_height = $dst_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
if($ext == 'png'){
imagealphablending($thumb, false);
$white = imagecolorallocatealpha($thumb, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($thumb,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($thumb, true);
}
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($ext == 'png'){
imagepng($thumb, $filename);
}else{
imagejpeg($thumb, $filename, 80);
}
return true;
}
CropImg("photo.png", "result.png", 300, 180);
?>

Categories