Error Resize image in Shared hosting (Cpanel) - php

I have a problem about resize image at hosting.
When i use function to resize image in Localhost, it's good.
But when i upload them to Cpanel. It's only work with small size picture. With bigger size(maybe 300kb), it doesn't work and doesn't
show any errors. How to fix it?
Please help me!
Command :
resize_image('max',"upload/tindang/".$Hinh,"upload/tindang/".$Hinh,600,600);
This is my function :
function resize_image_crop($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $width / $w;
$new_w = $width;
$new_h = $h * $ratio;
//if that created an image smaller than what we wanted, try the other way
if ($new_h < $height) {
$ratio = $height / $h;
$new_h = $height;
$new_w = $w * $ratio;
}
$image2 = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//check to see if cropping needs to happen
if (($new_h != $height) || ($new_w != $width)) {
$image3 = imagecreatetruecolor ($width, $height);
if ($new_h > $height) { //crop vertically
$extra = $new_h - $height;
$x = 0; //source x
$y = round($extra / 2); //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
} else {
$extra = $new_w - $width;
$x = round($extra / 2); //source x
$y = 0; //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
}
imagedestroy($image2);
return $image3;
} else {
return $image2;
}
}
function resize_image_max($image,$max_width,$max_height) {
$w = imagesx($image); //current width
$h = imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
// if (($w <= $max_width) && ($h <= $max_height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $max_width / $w;
$new_w = $max_width;
$new_h = $h * $ratio;
//if that didn't work
if ($new_h > $max_height) {
$ratio = $max_height / $h;
$new_h = $max_height;
$new_w = $w * $ratio;
}
$new_image = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($new_image,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
return $new_image;
}
function resize_image_force($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
$image2 = imagecreatetruecolor ($width, $height);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $width, $height, $w, $h);
return $image2;
}
function resize_image($method,$image_loc,$new_loc,$width,$height) {
if (!is_array(#$GLOBALS['errors'])) { $GLOBALS['errors'] = array(); }
if (!in_array($method,array('force','max','crop'))) { $GLOBALS['errors'][] = 'Invalid method selected.'; }
if (!$image_loc) { $GLOBALS['errors'][] = 'No source image location specified.'; }
else {
if ((substr(strtolower($image_loc),0,7) == 'http://') || (substr(strtolower($image_loc),0,7) == 'https://')) { /*don't check to see if file exists since it's not local*/ }
elseif (!file_exists($image_loc)) { $GLOBALS['errors'][] = 'Image source file does not exist.'; }
$extension = strtolower(substr($image_loc,strrpos($image_loc,'.')));
if (!in_array($extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid source file extension!'; }
}
if (!$new_loc) { $GLOBALS['errors'][] = 'No destination image location specified.'; }
else {
$new_extension = strtolower(substr($new_loc,strrpos($new_loc,'.')));
if (!in_array($new_extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid destination file extension!'; }
}
$width = abs(intval($width));
if (!$width) { $GLOBALS['errors'][] = 'No width specified!'; }
$height = abs(intval($height));
if (!$height) { $GLOBALS['errors'][] = 'No height specified!'; }
if (count($GLOBALS['errors']) > 0) { echo_errors(); return false; }
if (in_array($extension,array('.jpg','.jpeg'))) { $image = #imagecreatefromjpeg($image_loc); }
elseif ($extension == '.png') { $image = #imagecreatefrompng($image_loc); }
elseif ($extension == '.gif') { $image = #imagecreatefromgif($image_loc); }
elseif ($extension == '.bmp') { $image = #imagecreatefromwbmp($image_loc); }
if (!$image) { $GLOBALS['errors'][] = 'Image could not be generated!'; }
else {
$current_width = imagesx($image);
$current_height = imagesy($image);
if ((!$current_width) || (!$current_height)) { $GLOBALS['errors'][] = 'Generated image has invalid dimensions!'; }
}
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
if ($method == 'force') { $new_image = resize_image_force($image,$width,$height); }
elseif ($method == 'max') { $new_image = resize_image_max($image,$width,$height); }
elseif ($method == 'crop') { $new_image = resize_image_crop($image,$width,$height); }
if ((!$new_image) && (count($GLOBALS['errors'] == 0))) { $GLOBALS['errors'][] = 'New image could not be generated!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
$save_error = false;
if (in_array($extension,array('.jpg','.jpeg'))) { imagejpeg($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.png') { imagepng($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.gif') { imagegif($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.bmp') { imagewbmp($new_image,$new_loc) or ($save_error = true); }
if ($save_error) { $GLOBALS['errors'][] = 'New image could not be saved!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); #imagedestroy($new_image); echo_errors(); return false; }
imagedestroy($image);
imagedestroy($new_image);
return true;
}

Related

Resize image without lose quality when image is bigger

I use img uploader on my ftp.
If image large to 1024x768 i use script for resize.
But after resize lose quality.
Code from uploader.php:
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], "$upload_folder/" . $newname))
if($width>1024 || $height>768) {
require './image_resize.php';
echo (image_resize("$upload_folder/" . $newname, "$upload_folder/" . $newname, 1024, 768));
}
Code prom image_resize.php:
<?php ini_set('memory_limit','500M');
function image_resize($src, $dst, $width, $height, $crop=0){
if(!($pic = #getimagesize($src)))
return false;
$w = $pic[0];
$h = $pic[1];
$type = substr($pic['mime'], 6);
$func = 'imagecreatefrom' . $type;
if(!function_exists($func))
return false;
$img = $func($src);
if($crop){
if($w < $width && $h < $height)
return false;
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width && $h < $height)
return false;
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
if($type == "gif" || $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
$save = 'image' . $type;
$save($new, $dst);
return true;
}
It is impossible to reduce the size without losing quality :(
I found script for resize, working fine. I think this is a what I need :)
http://sanchiz.net/blog/resizing-images-with-php
But, one problem and please correct for me: If need resize PNG with transparent background this script remove transparent and add black background.
In comments posted modified script, but with this code not working compress function
I need modify this code for resize PNG without remove transparent background:
class SimpleImage {
public $image;
public $image_type;
public 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);
}
}
public function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 100, $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);
}
}
public 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);
}
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width, $height);
}
public function getHeight() {
return imagesy($this->image);
}
public function getWidth() {
return imagesx($this->image);
}
public 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;
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width, $height);
}
public function scale($scale) {
$width = $this->getWidth() * $scale / 100;
$height = $this->getheight() * $scale / 100;
$this->resize($width, $height);
}
Thank you
Since the default API may not be really effective when it comes to image handling, i suggest you use a library. Take a look at grafika
You can also use an external service for images resizing such as this repo
Flyimg.

how to resize the uploading image and moving to a folder

i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);

Image doesn't display

I have this code, I want to resize the picture, it manage to do the first one which 100x100 but not the others. I don't see why it doesn't work, it doesn't have any error. I'm a php newbie, doesn't really know what went wrong, but as you can see as the code does works for the 1st one but why doesn't work for the others?
<?php
function thumbnail($image, $width, $height) {
$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);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
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($thumbnail);
}
elseif($type == "image/jpeg") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$pic_size = array();
// Adjust size
$pic_size['height'][0] = 100;
$pic_size['width'][0] = 100;
$pic_size['height'][1] = 200;
$pic_size['width'][1] = 200;
$pic_size['height'][2] = 300;
$pic_size['width'][2] = 300;
$pic_size['height'][3] = 400;
$pic_size['width'][3] = 400;
$pic_size['height'][4] = 500;
$pic_size['width'][4] = 500;
$total_pic_size= count($pic_size['height']);
$x = 0;
foreach(array_keys($pic_size['height']) as $x) {
thumbnail($_GET["img"], $pic_size['width'][$x], $pic_size['height'][$x]);
echo '<img src="index.php?w='.$pic_size['width'][$x].'&h='.$pic_size['height'][$x].'&img='.$_GET["img"].'" />';
$x++;
}
?>
You iterate only two times, because
$total_pic_size= count($pic_size);// is 2
Change that to:
$total_pic_size= count($pic_size['height']);
Or use foreach:
foreach(array_keys($pic_size['height']) as $x)
And don't use COUNT_RECURSIVE here, it will return wrong number again, counting in the width and height keys.
Also thumbnail function has header call in it, which cannot be called after echo, which in your case, is called after echo, in your loop. You should see the warning saying "Headers already sent".
You can save the image to file and echo image with file path as a source. Remove the header calls and let your thumbnail function save it and return the file name, for example:
imagejpeg($thumbnail, $filename);
return $filename;
and use the output as src of the echoed image.
Your $total_pic_size is always 2.
$total_pic_size = count( $pic_size['width'] );
This will give you the correct number of items and the loop should run not only once.
You should also change the loop-condition:
while ($x <= $total_pic_size) {
#Update 1
You can try something like this:
// ...
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
$img = $_GET["img"];
foreach ($pic_sizes as $pic_size) {
thumbnail($img, $pic_size['width'], $pic_size['height']);
echo '<img src="index.php?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'" />';
}
#Update 2:
You already accepted another answere, but maybe this is also helpful for you. i found some more errors and logic-problems in your code... the code below works (without saving the thumbs).
<?php
function thumbnail($image, $width, $height) {
$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);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
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($thumbnail);
}
elseif($type == "image/png") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$img = $_GET["img"];
$gen = #$_GET["gen"];
$w = #$_GET["w"];
$h = #$_GET["h"];
if ( !$gen ) {
$pic_sizes = array();
// Adjust size
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
foreach ($pic_sizes as $pic_size) {
echo '<img src="'.$_SERVER['PHP_SELF'].'?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'&gen=1" />';
}
} else {
thumbnail($img, $w, $h);
}

Image Resizing: Poor jpeg quality and black PNG backgrounds

Final: I've decided to basically use this: http://shiftingpixel.com/2008/03/03/smart-image-resizer/
As it handles everything, Ive turned caching off and do this in the admin controllers:
$image = file_get_contents(SITE_ADMIN_IMAGE.'/SmartImage.php?width='.$this->thumb_width.'&height='.$this->thumb_height.'&image=/images/'.$this->image_directory.'/'.$formData['image_url'].'');
file_put_contents(ROOT_PATH.'/public/images/'.$this->image_directory.'/thumb/'.$formData['image_url'], $image);
EDIT: I found this works, however it creates very sharp edges, it doesn't look right.
imagecolortransparent($dstImage, $background);
imagealphablending($dstImage, false);
$colorTransparent = imagecolorallocatealpha($dstImage, 0, 0, 0, 127);
imagefill($dstImage, 0, 0, $colorTransparent);
imagesavealpha($dstImage, true);
imagepng($dstImage, $toWhere);
Ideas?
Hello,
I have two issues with my class, basically the quality of the jpeg images is quite poor, but I'm not sure if thats down to my ratio resizing. Ideally I'd like this class to be strict with image sizes and crop into them, but I cant get my head around it.
My main issue is that pngs always have a black bg, does anyone have experience with this happening?
<?php
class OpenSource_ImageResize {
function __construct($theFile, $toWhere, $mime, $extension, $newWidth, $newHeight) {
if ($mime == NULL) {
$mime = getimagesize($theFile);
$mime = $mime['mime'];
}
if ($mime == 'image/jpeg') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefromjpeg($theFile);
} else {
return copy($theFile, $toWhere);
throw new exception('Could not create jpeg');
return false;
}
} else if ($mime == 'image/png') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefrompng($theFile);
} else {
return copy($theFile, $toWhere);
//throw new exception('Could not create png');
return false;
}
} else if ($mime == 'image/gif') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefromgif ($theFile);
} else {
return copy($theFile, $toWhere);
//throw new exception('Could not create gif');
return false;
}
} else {
throw new exception('Not a valid mime type');
return false;
}
$oldX = imageSX($sourceImage);
$oldY = imageSY($sourceImage);
if ($newWidth == NULL) {
$thumbHeight = $newHeight;
$thumbWidth = round($newHeight/($oldY/$oldX));
} else
if ($oldX > $oldY) {
$thumbWidth = $newWidth;
$thumbHeight = $oldY * ($newHeight/$oldX);
}
if ($oldX < $oldY) {
$thumbWidth = round($newHeight/($oldY/$oldX));
$thumbHeight = $newHeight;
}
if ($oldX == $oldY) {
$thumbWidth = $newWidth;
$thumbHeight = $newHeight;
}
if (!gd_info()) {
$dstImage = ImageCreate($thumbWidth, $thumbHeight);
imagecopyresized($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $oldX, $oldY);
} else {
$dstImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);
imagecopyresampled($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $oldX, $oldY);
}
if ($mime == 'image/png') {
$xparent = imagecolorresolvealpha($dstImage, 255,2,240, 0) ;
imagecolortransparent($dstImage,$xparent);
imagealphablending($dstImage,true);
imagepng($dstImage, $toWhere);
} else if ($mime == 'image/jpeg') {
imagejpeg($dstImage, $toWhere);
} else if ($mime == 'image/gif') {
imagegif ($dstImage, $toWhere);
}
imagedestroy($dstImage);
imagedestroy($sourceImage);
return true;
}
}
Regarding JPEG image quality you need to make use of the third argument in imagejpeg():
imagejpeg($dstImage, $toWhere, 90); // any value above 85 should be fine
Regarding PNG transparency, you're doing it wrong. Your script is horrible and has fundamental problems, I'm gonna leave you with a revised one that fixes both of your problems. It can still be further optimized but I choose to leave some of your original less important mistakes so you don't feel lost:
class OpenSource_ImageResize
{
// $extension is not used?
function __construct($theFile, $toWhere, $mime, $extension, $newWidth, $newHeight)
{
$sourceImage = ImageCreateFromString(file_get_contents($theFile));
if (is_resource($sourceImage))
{
$info = getimagesize($theFile);
if (is_null($mime))
{
$mime = $info['mime'];
}
if ($info[0] <= $newWidth && $info[1] <= $newHeight)
{
imagedestroy($sourceImage);
return copy($theFile, $toWhere);
}
if (is_null($newWidth))
{
$thumbHeight = $newHeight;
$thumbWidth = round($newHeight/($info[1]/$info[0]));
}
else if ($info[0] > $info[1])
{
$thumbWidth = $newWidth;
$thumbHeight = $info[1] * ($newHeight/$info[0]);
}
if ($info[0] < $info[1])
{
$thumbWidth = round($newHeight/($info[1]/$info[0]));
$thumbHeight = $newHeight;
}
if ($info[0] == $info[1])
{
$thumbWidth = $newWidth;
$thumbHeight = $newHeight;
}
$dstImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);
/* fix PNG transparency issues */
ImageFill($dstImage, 0, 0, IMG_COLOR_TRANSPARENT);
ImageSaveAlpha($dstImage, true);
ImageAlphaBlending($dstImage, true);
imagecopyresampled($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $info[0], $info[1]);
switch ($mime)
{
case 'image/png':
imagepng($dstImage, $toWhere, 9); // compress it (level 1 to 9)
break;
case 'image/jpeg':
imagejpeg($dstImage, $toWhere, 90); // quality = 90 (1 to 100, default is "about" 75)
break;
case 'image/gif':
imagegif($dstImage, $toWhere);
break;
}
imagedestroy($dstImage);
imagedestroy($sourceImage);
return true;
}
}
}
I'm sorry for not explicitly pointing out your mistakes but they are so many and it's 3 AM here, need to get some sleep - study it and read the manual, if you have any doubts let me know.
Musty define in your class png background color.You can also change the background color of jpg and other files after defining the background color.
this link will take you to a simple function that will either crop-to-fit, or letter box the image during resize based on the function's arguments. it also has a pretty thorough explaination as to what the function is doing.
http://www.spotlesswebdesign.com/blog.php?id=1
Edit: fixed link.

CAn't resize image with GDlib2

I'm trying to resize an image of more than 3000px in width, it uploads fine if i do not resize it, but as soon as I resize the image it does not want to upload and resize, this is funny and I can't seem to understnd, since if the width of the image is alot smaller everthing works just fine. Are there limitations to this?
Try this... Not Using GD but i think it will work for u.
<?php
function Image($image, $crop = null, $size = null) {
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image) === true) {
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
/*
CROP (Aspect Ratio) Section
*/
if (is_null($crop) === true) {
$crop = array($width, $height);
} else {
$crop = array_filter(explode(':', $crop));
if (empty($crop) === true) {
$crop = array($width, $height);
} else {
if ((empty($crop[0]) === true) || (is_numeric($crop[0]) === false)) {
$crop[0] = $crop[1];
} else if ((empty($crop[1]) === true) || (is_numeric($crop[1]) === false)) {
$crop[1] = $crop[0];
}
}
$ratio = array(0 => $width / $height, 1 => $crop[0] / $crop[1]);
if ($ratio[0] > $ratio[1]) {
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
}
else if ($ratio[0] < $ratio[1]) {
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
}
/*
Resize Section
*/
if (is_null($size) === true) {
$size = array($width, $height);
}
else {
$size = array_filter(explode('x', $size));
if (empty($size) === true) {
$size = array(imagesx($image), imagesy($image));
} else {
if ((empty($size[0]) === true) || (is_numeric($size[0]) === false)) {
$size[0] = round($size[1] * $width / $height);
} else if ((empty($size[1]) === true) || (is_numeric($size[1]) === false)) {
$size[1] = round($size[0] * $height / $width);
}
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result) === true) {
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $size[0], $size[1], $width, $height);
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
header('Content-Type: image/jpeg');
Image('image.jpg', '2:1', '1200x');
?>

Categories