Creating a thumbnail from an uploaded image showing black background - php

I'm getting image thumbnail but background is black.i could not understand why it is happening.Though i found this script in stackoverflow.
Is it problem in gd library.i'm using xampp
makeThumbnails($upload_dir.$new_nm,227,182,$upload_dir_thumb.$new_nm);
function makeThumbnails($src,$w,$h,$dir)
{
$arr_image_details = getimagesize($src);
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $w;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $h;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($w - $new_width) / 2);
$dest_y = intval(($h - $new_height) / 2);
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($src);
$new_image = imagecreatetruecolor($w, $h);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $dir);
}

I think You are doing wrong with $old_image = $imgcreatefrom($src)
What will return `$imgcreatefrom($src)` check it.

function makethumb($raw,$tw,$th,$DestFolder)
{
$arr_image_details = getimagesize($raw);
$CurWidth = $arr_image_details[0];
$CurHeight = $arr_image_details[1];
//print_r($arr_image_details);exit;
switch(strtolower($arr_image_details['mime']))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($raw);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($raw);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($raw);
break;
default:
$processImage = false; //image format is not supported!
}
if($tw >=$th )
{
$MaxSize=$tw;
}else{
$MaxSize=$th;
}
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
if(imagecopyresampled($NewCanves, $CreatedImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($arr_image_details['mime']))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,90);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}

Related

Phalcon PNG to JPG and remove transparent background image

I'm using Phalcon PHP Phalcon\Images\Adapter\GD and I have a problem with the PNG to JPG.
When I upload a PNG image on my server, I resize this image, I set the background color in white with the background method $myImage->background('#FFFFFF') but this background is now black... I don't understand why and after I split the extension .PNG and I add .JPG.
How can I do to set the background color image to white ?
Try this it worked for me :
function img_resize($file,$width=0,$height=0,$proportional=false,$output='file' ) {
if ( $height <= 0 && $width <= 0 ) return false;
# Setting defaults and meta
$info= getimagesize($file);
$image= '';
$final_width= 0;
$final_height= 0;
list($width_old, $height_old) = $info;
# Calculating proportionality
if ($proportional) {
if ($width == 0) $factor = $height/$height_old;
elseif ($height == 0) $factor = $width/$width_old;
else $factor = min( $width / $width_old, $height / $height_old );
$final_width = round( $width_old * $factor );
$final_height = round( $height_old * $factor );
}
else {
$final_width = ( $width <= 0 ) ? $width_old : $width;
$final_height = ( $height <= 0 ) ? $height_old : $height;
}
# Loading image to memory according to type
switch ( $info[2] ) {
case IMAGETYPE_GIF: $image = imagecreatefromgif($file); break;
case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file); break;
case IMAGETYPE_PNG: $image = imagecreatefrompng($file); break;
default: return false;
}
# This is the resizing/resampling/transparency-preserving magic
$image_resized = imagecreatetruecolor( $final_width, $final_height );
if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
$transparency = imagecolortransparent($image);
if ($transparency >= 0) {
$transparent_color = imagecolorsforindex($image, $trnprt_indx);
$transparency = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($image_resized, 0, 0, $transparency);
imagecolortransparent($image_resized, $transparency);
}
elseif ($info[2] == IMAGETYPE_PNG) {
imagealphablending($image_resized, false);
$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
imagefill($image_resized, 0, 0, $color);
imagesavealpha($image_resized, true);
}
}
imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);
# Preparing a method of providing result
switch ( strtolower($output) ) {
case 'browser':
$mime = image_type_to_mime_type($info[2]);
header("Content-type: $mime");
$output = NULL;
break;
case 'file':
$output = $file;
break;
case 'return':
return $image_resized;
break;
default:
break;
}
# Writing image according to type to the output destination
switch ( $info[2] ) {
case IMAGETYPE_GIF: imagegif($image_resized, $output); break;
case IMAGETYPE_JPEG: imagejpeg($image_resized, $output); break;
case IMAGETYPE_PNG: imagepng($image_resized, $output); break;
default: return false;
}
return true;
}
Call function like below :
$image = new Phalcon\Image\Adapter\GD(YOUR_IMAGE_PATH);
$a=img_resize($image->getRealpath(),$image->getWidth(),$image->getHeight());
Some code might not necessary for you.

Image resize bug

I have inherited a function which resizes images. It works well in most cases, but for some reason, in some cases the result of resizing the image is totally different than the image initially contained. The function is as follows:
function image_resize($source, $destination, $width, $height, $resizeMode='fit', $type = 'jpeg', $options = array()) {
$defaults = array(
'output' => 'file',
'isFile' => true,
'quality' => '100',
'preserveAnimation' => false,
'offsetTop' => 0,
'offsetLeft' => 0,
'offsetType' => 'percent'
);
foreach ($defaults as $k => $v) {
if (!isset($options[$k])) {
$options[$k] = $v;
}
}
if ($options['isFile']) {
$image_info = getimagesize($source);
$image = null;
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
case IMAGETYPE_BMP:
$image = imagecreatefromwbmp($source);
break;
default :
return false;
}
} else {
$image = imagecreatefromstring($source);
}
//we have an image resource
$iwidth = imagesx($image);
$iheight = imagesy($image);
//We need $width and $height for this call
if (QM::isAcceptableProfilePhotoSize($width, $height) == false)
{
throw new Exception("Size of ".$width."x".$height." is not supported");
}
//determine ratios
$wratio = $width / $iwidth;
$hratio = $height / $iheight;
$mratio = min(array($wratio, $hratio));
$rimage = null;
switch ($resizeMode) {
case 'fit':
$rimage = imagecreatetruecolor($iwidth * $mratio, $iheight * $mratio);
$image = imagecopyresampled($rimage, $image, 0, 0, 0, 0, $iwidth * $mratio, $iheight * $mratio, $iwidth, $iheight);
break;
case 'crop':
$rratio = $width / $height;
if ($rratio < 1) {
$nwidth = $iwidth;
$nheight = $iwidth * 1/$rratio;
if ($nheight>$iheight) {
$nwidth = $nwidth*$iheight/$nheight;
$nheight = $iheight;
}
} else {
$nwidth = $iheight*$rratio;
$nheight = $iheight;
if ($nwidth>$iwidth) {
$nheight = $nheight*$iwidth/$nwidth;
$nwidth = $iwidth;
}
}
switch ($options['offsetType']) {
case 'percent':
$sx = ($iwidth-$nwidth)*$options['offsetLeft']/100;
$sy = ($iheight-$nheight)*$options['offsetTop']/100;
break;
default :
return false;
}
$rimage = imagecreatetruecolor($width, $height);
$image = imagecopyresampled($rimage, $image, 0, 0, $sx, $sy, $width, $height, $nwidth, $nheight);
break;
default :
return false;
break;
}
if (!is_writeable(dirname($destination))) {
throw new Exception(getcwd(). "/" .dirname($destination)." is not writeable");
}
switch ($options['output']) {
case 'file':
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
return imagejpeg($rimage, $destination, $options['quality']);
case IMAGETYPE_PNG:
return imagepng($rimage, $destination, 0);
case IMAGETYPE_GIF:
return imagegif($rimage, $destination);
case IMAGETYPE_BMP:
return imagejpeg($rimage, $destination, $options['quality']);
default :
return false;
break;
}
return true;
break;
default :
return false;
break;
}
}
Example image causing the problem:
This image is successfully uploaded, but when I try to resize it, the resulting image is:
I call the function this way:
image_resize($ofile, $cfile, $width, $height, 'crop', 'jpeg');
Where $ofile is the original file, $cfile is the planned destination, $width is the desired width (90 in this case), $height is the desired height (90 in this case), 'crop' is the selected strategy and 'jpeg' is a certain $type value, which is unused in the function (as I have mentioned, I have inherited the code). Also, the only example where the problem could be reproduced is the attached image, which is a png, other png files are uploaded correctly, so I do not understand the cause of the issue and do not know how to solve it. Can anybody describe the cause of the problem? I have searched and experimented for a long while without achieving success.
i tried your "image_resize" function with your bird picture, and it works perfectly fine on my computer,
whether i set the source image to jpg or png, it works as expected :
However why not choosing "fit" instead of "crop" like so :
image_resize($ofile, $cfile, $width = 90, $height = 90, 'fit', 'jpeg');
Edit: based on other people's issues about getting black image after resizing PNG, this would be the correction:
function image_resize($source, $destination, $width, $height, $resizeMode='fit', $type = 'jpeg', $options = array()) {
$defaults = array(
'output' => 'file',
'isFile' => true,
'quality' => '100',
'preserveAnimation' => false,
'offsetTop' => 0,
'offsetLeft' => 0,
'offsetType' => 'percent'
);
foreach ($defaults as $k => $v) {
if (!isset($options[$k])) {
$options[$k] = $v;
}
}
if ($options['isFile']) {
$image_info = getimagesize($source);
$image = null;
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
case IMAGETYPE_BMP:
$image = imagecreatefromwbmp($source);
break;
default :
return false;
}
} else {
$image = imagecreatefromstring($source);
}
//we have an image resource
$iwidth = imagesx($image);
$iheight = imagesy($image);
//determine ratios
$wratio = $width / $iwidth;
$hratio = $height / $iheight;
$mratio = min(array($wratio, $hratio));
$rimage = null;
switch ($resizeMode) {
case 'fit':
$rimage = imagecreatetruecolor($iwidth * $mratio, $iheight * $mratio);
imagealphablending( $rimage, false );
imagesavealpha( $rimage, true );
$image = imagecopyresampled($rimage, $image, 0, 0, 0, 0, $iwidth * $mratio, $iheight * $mratio, $iwidth, $iheight);
break;
case 'crop':
$rratio = $width / $height;
if ($rratio < 1) {
$nwidth = $iwidth;
$nheight = $iwidth * 1/$rratio;
if ($nheight>$iheight) {
$nwidth = $nwidth*$iheight/$nheight;
$nheight = $iheight;
}
} else {
$nwidth = $iheight*$rratio;
$nheight = $iheight;
if ($nwidth>$iwidth) {
$nheight = $nheight*$iwidth/$nwidth;
$nwidth = $iwidth;
}
}
switch ($options['offsetType']) {
case 'percent':
$sx = ($iwidth-$nwidth)*$options['offsetLeft']/100;
$sy = ($iheight-$nheight)*$options['offsetTop']/100;
break;
default :
return false;
}
$rimage = imagecreatetruecolor($width, $height);
imagealphablending( $rimage, false );
imagesavealpha( $rimage, true );
$image = imagecopyresampled($rimage, $image, 0, 0, $sx, $sy, $width, $height, $nwidth, $nheight);
break;
default :
return false;
break;
}
if (!is_writeable(dirname($destination))) {
throw new Exception(getcwd(). "/" .dirname($destination)." is not writeable");
}
switch ($options['output']) {
case 'file':
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
return imagejpeg($rimage, $destination, $options['quality']);
case IMAGETYPE_PNG:
return imagepng($rimage, $destination, 0);
case IMAGETYPE_GIF:
return imagegif($rimage, $destination);
case IMAGETYPE_BMP:
return imagejpeg($rimage, $destination, $options['quality']);
default :
return false;
break;
}
return true;
break;
default :
return false;
break;
}
}

PHP PNG Photo upload that keeps transparency

I'm completely stumpted on this one... I need a photo upload script that keeps the transparency of png files. At the moment the transparent areas are black. Any help is greatly appreciated. Here is my code:
if(isset($_POST)) {
require_once('siteInfo.php');
session_start();
$ThumbSquareSize = 90;
$BigImageMaxSize = $_POST['size'];
$ThumbPrefix = "thumb_";
$DestinationDirectory = '../Uploads/';
$Quality = 100;
if (!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])) {
die('Please select a file.');
}
$RandomNumber = rand(0, 9999999999);
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size'];
$TempSrc = $_FILES['ImageFile']['tmp_name'];
$ImageType = $_FILES['ImageFile']['type'];
switch (strtolower($ImageType)) {
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
// die('Unsupported file format. Please upload a PNG, GIF, or JPG file.'); //output error and exit
}
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
if (resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) {
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) {
echo 'Error Creating thumbnail';
}
$query = "Update Content set ".$_POST['field']."='".$NewImageName."' WHERE ID=".$_POST['ID'];
mysqli_query($dbc, $query);
mysqli_close($dbc);
echo 'Uploaded file: <span>'.$NewImageName.'</span>.';
} else {
die('Resize Error');
}
}
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType) {
if ($CurWidth <= 0 || $CurHeight <= 0) {
return false;
}
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
if (imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)) {
switch(strtolower($ImageType)) {
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if (is_resource($NewCanves)) { imagedestroy($NewCanves); }
return true;
}
}
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType){
if ($CurWidth <= 0 || $CurHeight <= 0) {
return false;
}
if ($CurWidth>$CurHeight) {
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
} else {
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if (imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)) {
switch(strtolower($ImageType)) {
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if (is_resource($NewCanves)) { imagedestroy($NewCanves); }
return true;
}
}
I added the following to the "resizeImage" function:
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
imagealphablending($SrcImage, true);
And that fixed the problem.

Resize an image and save with imagejpeg()

iam trying to resize an imageto a thumbnail with php! I get no errors but it won't save the thumbnail on my server. The code is:
#Resize image
function resize($input_dir, $cur_file, $newwidth, $output_dir)
{
$filename = $input_dir.'/'.$cur_file;
$format='';
if(preg_match("/.jpg/i", $filename))
{
$format = 'image/jpeg';
}
if (preg_match("/.gif/i", $filename))
{
$format = 'image/gif';
}
if(preg_match("/.png/i", $filename))
{
$format = 'image/png';
}
if($format!='')
{
list($width, $height) = getimagesize($filename);
$newheight=$height*$newwidth/$width;
switch($format)
{
case 'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case 'image/gif';
$source = imagecreatefromgif($filename);
break;
case 'image/png':
$source = imagecreatefrompng($filename);
break;
}
$thumb = imagecreatetruecolor($newwidth,$newheight);
imagealphablending($thumb, false);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, 'thumb_'.$cur_file);
}
}
My function looks like:
resize(plugins_url().'/MyImagePlugin/img', 'testimg.jpg', "200");
The Image is in the Folder "img" in my Plugin Dic. The wired thing is ,that i don't get any erros?! CHMOD is 777 for img-folder.
Any help would be appreciated.
You are not using any path when you save the image in the line:
imagejpeg($thumb, 'thumb_'.$cur_file);
$cur_file is set to testing.jpg.
You should add the path to the filename or it will be attempoting to create it in whatever the current directory is.
Changes are something like :
function resize($input_dir, $cur_file, $newwidth, $output_dir = "" )
{
if($output_dir == "") $output_dir = $input_dir;
.....
imagejpeg($thumb, $output_dir.'/thumb_'.$cur_file);
}
}
I know that this is not your way of doing but iam sure it can help you.
if (isset($_FILES['image']['name']))
{
$saveto = "dirname/file.jpg";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 500;
\\ you can change this to desired product for height and width.
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}

image compression in php

I am compressing an image using following class..
<?php
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename,$image_type=IMAGETYPE_JPEG,$compression=75,$permissions=null){
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image,$this->image,0,0,0,0,$width,$height,$this->getWidth(),$this->getHeight());
$this->image = $new_image;
}
}
?>
And my php code looks like..
include_once(ROOT.'/library/SimpleImage.php')
$image = new SimpleImage();
$image->load($image_name);
$image->resizeToWidth(100);
$image->save($image_name);
Now the problem is that my images are getting compressed, but their original color combination get lost...
Don't know what to do..??
Please suggest another class for image compression.
This is a function I coded a long time ago, it's not realy optimized but it should do the trick. Works for various mime types and allows you to save the modified image into a new location. You can easily simplify it if you need less features.
public function resizePicture($path, $new_path, $new_width, $new_height, $proportion = false) {
$size = getimagesize($path);
$x = 0;
$y = 0;
switch($size['mime']) {
case 'image/jpeg':
$picture = imagecreatefromjpeg($path);
break;
case 'image/png':
$picture = imagecreatefrompng($path);
break;
case 'image/gif':
$picture = imagecreatefromgif($path);
break;
default:
return false;
break;
}
$width = $size[0];
$height = $size[1];
$frame = imagecreatetruecolor($new_width, $new_height);
if($size['mime'] == 'image/jpeg') {
$bg = imagecolorallocate($frame, 255, 255, 255);
imagefill($frame, 0, 0, $bg);
} else if($size['mime'] == 'image/gif' or $size['mime'] == 'image/png') {
imagealphablending($picture, false);
imagesavealpha($picture, true);
imagealphablending($frame, false);
imagesavealpha($frame, true);
}
if($width < $new_width and $height < $new_height) {
$x = ($new_width - $width) / 2;
$y = ($new_height - $height) / 2;
imagecopy($frame, $picture, $x, $y, 0, 0, $width, $height);
} else {
if($proportion and $width != $height) {
if($width > $height) {
$old_height = $new_height;
$new_height = $height * $new_width / $width;
$y = abs($old_height - $new_height) / 2;
} else {
$old_width = $new_width;
$new_width = $width * $new_height / $height;
$x = abs($old_width - $new_width) / 2;
}
}
imagecopyresampled($frame, $picture, $x, $y, 0, 0, $new_width, $new_height, $width, $height);
}
switch($size['mime']) {
case 'image/jpeg':
imagejpeg($frame, $new_path, 85);
break;
case 'image/png':
imagepng($frame, $new_path, 8);
break;
case 'image/gif':
imagegif($frame, $new_path);
break;
default:
return false;
break;
}
}
I use SimpleImage.php and find it a helpful little script, but I had to change the value of $compression to 100 in save function.
Perhaps compressing certain formats reduces number of colors, but by setting $compression to a 100 you tell the script "Don't compress!"
After that the images look like they suppose to.

Categories