I found a PHP script online which helps me to create a thumbnail of an uploaded image, there is only one problem: I don't know how to change the outcome size of the thumbnail. I found the tutorial at: http://www.w3schools.in/php/image-upload-and-generate-thumbnail-using-ajax-in-php/
Can anyone help me to change the outcome size of the thumbnail?
Here is my code so far:
<?php
function createDir($path){
if (!file_exists($path)) {
$old_mask = umask(0);
mkdir($path, 0777, TRUE);
umask($old_mask);
}
}
function createThumb($path1, $path2, $file_type, $new_w, $new_h, $squareSize = ''){
/* read the source image */
$source_image = FALSE;
if (preg_match("/jpg|JPG|jpeg|JPEG/", $file_type)) {
$source_image = imagecreatefromjpeg($path1);
}
elseif (preg_match("/png|PNG/", $file_type)) {
if (!$source_image = #imagecreatefrompng($path1)) {
$source_image = imagecreatefromjpeg($path1);
}
}
elseif (preg_match("/gif|GIF/", $file_type)) {
$source_image = imagecreatefromgif($path1);
}
if ($source_image == FALSE) {
$source_image = imagecreatefromjpeg($path1);
}
$orig_w = imageSX($source_image);
$orig_h = imageSY($source_image);
if ($orig_w < $new_w && $orig_h < $new_h) {
$desired_width = $orig_w;
$desired_height = $orig_h;
} else {
$scale = min($new_w / $orig_w, $new_h / $orig_h);
$desired_width = ceil($scale * $orig_w);
$desired_height = ceil($scale * $orig_h);
}
if ($squareSize != '') {
$desired_width = $desired_height = $squareSize;
}
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
// for PNG background white----------->
$kek = imagecolorallocate($virtual_image, 255, 255, 255);
imagefill($virtual_image, 0, 0, $kek);
if ($squareSize == '') {
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $orig_w, $orig_h);
} else {
$wm = $orig_w / $squareSize;
$hm = $orig_h / $squareSize;
$h_height = $squareSize / 2;
$w_height = $squareSize / 2;
if ($orig_w > $orig_h) {
$adjusted_width = $orig_w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($virtual_image, $source_image, -$int_width, 0, 0, 0, $adjusted_width, $squareSize, $orig_w, $orig_h);
}
elseif (($orig_w <= $orig_h)) {
$adjusted_height = $orig_h / $wm;
$half_height = $adjusted_height / 2;
imagecopyresampled($virtual_image, $source_image, 0,0, 0, 0, $squareSize, $adjusted_height, $orig_w, $orig_h);
} else {
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $squareSize, $squareSize, $orig_w, $orig_h);
}
}
if (#imagejpeg($virtual_image, $path2, 90)) {
imagedestroy($virtual_image);
imagedestroy($source_image);
return TRUE;
} else {
return FALSE;
}
}
?>
the function gets called by the following lines of code:
<?php
include('./functions.php');
/*defined settings - start*/
ini_set("memory_limit", "99M");
ini_set('post_max_size', '20M');
ini_set('max_execution_time', 600);
define('IMAGE_SMALL_DIR', './uploades/small/');
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_DIR', './uploades/medium/');
define('IMAGE_MEDIUM_SIZE', 250);
/*defined settings - end*/
if(isset($_FILES['image_upload_file'])){
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_upload_file']["error"] > 0) {
$output['error']= "Error in File";
}
elseif (!in_array($_FILES['image_upload_file']["type"], $allowedImageType)) {
$output['error']= "You can only upload JPG, PNG and GIF file";
}
elseif (round($_FILES['image_upload_file']["size"] / 1024) > 4096) {
$output['error']= "You can upload file size up to 4 MB";
} else {
/*create directory with 777 permission if not exist - start*/
createDir(IMAGE_SMALL_DIR);
createDir(IMAGE_MEDIUM_DIR);
/*create directory with 777 permission if not exist - end*/
$path[0] = $_FILES['image_upload_file']['tmp_name'];
$file = pathinfo($_FILES['image_upload_file']['name']);
$fileType = $file["extension"];
$desiredExt='jpg';
$fileNameNew = rand(333, 999) . time() . ".$desiredExt";
$path[1] = IMAGE_MEDIUM_DIR . $fileNameNew;
$path[2] = IMAGE_SMALL_DIR . $fileNameNew;
if (createThumb($path[0], $path[1], $fileType, IMAGE_MEDIUM_SIZE, IMAGE_MEDIUM_SIZE,IMAGE_MEDIUM_SIZE)) {
if (createThumb($path[1], $path[2],"$desiredExt", IMAGE_SMALL_SIZE, IMAGE_SMALL_SIZE,IMAGE_SMALL_SIZE)) {
$output['status']=TRUE;
$output['image_medium']= $path[1];
$output['image_small']= $path[2];
}
}
}
echo json_encode($output);
}
?>
I saw that you found the answer to your own problem. I wanted to add some additional insight.
The Right Way
Ideally you should be passing a param to the method as you can reset it if desired:
$imageSize = 100; // size
createThumb($path[0], $path[1], $fileType, $imageSize, $imageSize, $imageSize);
The Wrong Way
The script above is using constants. They are outlined with the define method. IE.
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_SIZE', 250);
Change the number to your desired size. Ie
define('IMAGE_SMALL_SIZE', 150);
In this particular use case, the constants are still being passed into the function which defeats the need for a constant.
Related
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;
}
I have that free php code-function (of Pedro Pinheiro https://github.com/pedroppinheiro)
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}`
it creates thumbnails from single image file when you call function like this
$success = createThumbnail(__DIR__.DIRECTORY_SEPARATOR.'image.jpg', __DIR__.DIRECTORY_SEPARATOR.'image_thumb.jpg', 60, 60, array(255,255,255));
It is okay for single image file but I want it to convert all images in a folder what should I do? When I use for each it does not work.
I am trying to develop a joomla module I have that code that grabbing images
static function getList($params) {
$filter = '\.png$|\.gif$|\.jpg$|\.bmp$';
$path = $params->get('path');
$files = JFolder::files(JPATH_BASE.$path,$filter);
$i=0;
$lists = array();
foreach ($files as $file) {
$lists[$i]['title'] = JFile::stripExt($file);
$lists[$i]['image'] = JURI::base().str_replace(DS,'/',substr($path,1)).'/'.$file;
$i++;
}
return $lists;
}
Then I add this to create thumbnails
<?php
$filepath=JUri::root() . '/images/';
$thumbpath=JUri::root() . '/images/thumbs/';
$success=createThumbnail($filepath, $thumbpath, 160, 160, array(0,0,0));
?>
<?php foreach ($lists as $item):?>
<div>
<?php echo $success;?>
</div>
<?php endforeach; ?>
But it fails. thanks in advance.
I'm using the newest version of Prestashop (1.6.1.5), and I've got some problems with quality of product images.
While resizing (creating thumbnails like large_default, home_default etc) grey stripes appears on destination image.
I followed prestashop code and noticed that it happens after imagecopyresized() function, I tried to replace it with imagecopyresampled() but it doesn't help much.
Here is a link to the original image http://postimg.org/image/ib42bh81t, and here is a link to resized one (the one with grey stripes) http://postimg.org/image/i3tpda7sx
Prestashop resize() method:
public static function resize($src_file, $dst_file, $dst_width = null, $dst_height = null, $file_type = 'jpg',
$force_type = false, &$error = 0, &$tgt_width = null, &$tgt_height = null, $quality = 5,
&$src_width = null, &$src_height = null)
{
if (PHP_VERSION_ID < 50300) {
clearstatcache();
} else {
clearstatcache(true, $src_file);
}
if (!file_exists($src_file) || !filesize($src_file)) {
return !($error = self::ERROR_FILE_NOT_EXIST);
}
list($tmp_width, $tmp_height, $type) = getimagesize($src_file);
$rotate = 0;
if (function_exists('exif_read_data') && function_exists('mb_strtolower')) {
$exif = #exif_read_data($src_file);
if ($exif && isset($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$src_width = $tmp_width;
$src_height = $tmp_height;
$rotate = 180;
break;
case 6:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = -90;
break;
case 8:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = 90;
break;
default:
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
// If PS_IMAGE_QUALITY is activated, the generated image will be a PNG with .jpg as a file extension.
// This allow for higher quality and for transparency. JPG source files will also benefit from a higher quality
// because JPG reencoding by GD, even with max quality setting, degrades the image.
if (Configuration::get('PS_IMAGE_QUALITY') == 'png_all'
|| (Configuration::get('PS_IMAGE_QUALITY') == 'png' && $type == IMAGETYPE_PNG) && !$force_type) {
$file_type = 'png';
}
if (!$src_width) {
return !($error = self::ERROR_FILE_WIDTH);
}
if (!$dst_width) {
$dst_width = $src_width;
}
if (!$dst_height) {
$dst_height = $src_height;
}
$width_diff = $dst_width / $src_width;
$height_diff = $dst_height / $src_height;
$ps_image_generation_method = Configuration::get('PS_IMAGE_GENERATION_METHOD');
if ($width_diff > 1 && $height_diff > 1) {
$next_width = $src_width;
$next_height = $src_height;
} else {
if ($ps_image_generation_method == 2 || (!$ps_image_generation_method && $width_diff > $height_diff)) {
$next_height = $dst_height;
$next_width = round(($src_width * $next_height) / $src_height);
$dst_width = (int)(!$ps_image_generation_method ? $dst_width : $next_width);
} else {
$next_width = $dst_width;
$next_height = round($src_height * $dst_width / $src_width);
$dst_height = (int)(!$ps_image_generation_method ? $dst_height : $next_height);
}
}
if (!ImageManager::checkImageMemoryLimit($src_file)) {
return !($error = self::ERROR_MEMORY_LIMIT);
}
$tgt_width = $dst_width;
$tgt_height = $dst_height;
$dest_image = imagecreatetruecolor($dst_width, $dst_height);
// If image is a PNG and the output is PNG, fill with transparency. Else fill with white background.
if ($file_type == 'png' && $type == IMAGETYPE_PNG) {
imagealphablending($dest_image, false);
imagesavealpha($dest_image, true);
$transparent = imagecolorallocatealpha($dest_image, 255, 255, 255, 127);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $transparent);
} else {
$white = imagecolorallocate($dest_image, 255, 255, 255);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $white);
}
$src_image = ImageManager::create($type, $src_file);
if ($rotate) {
$src_image = imagerotate($src_image, $rotate, 0);
}
if ($dst_width >= $src_width && $dst_height >= $src_height) {
imagecopyresized($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height);
} else {
ImageManager::imagecopyresampled($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height, $quality);
}
$write_file = ImageManager::write($file_type, $dest_image, $dst_file);
#imagedestroy($src_image);
return $write_file;
}
I also tried to change quality parameter to 100 or even changed image format to PNG in prestashop - no changes.
What else can I change to fix this quality issues? Any ideas?
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);
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.