Problem when uploading and saving image in database - php

Hello guys and ladies,
I am trying to upload and save images in a database. My code is working, but when I test it then after three or four times the image will save partially like this:
In my code I can save up to 12 images (if uploaded). And i'm testing with 4 images.
What am I doing wrong? Is it a memory problem? And if it is..what is causing it?
thank you for helping.
My code is:
//save up to 12 images in database
for($i=1;$i<=12;$i++){
$fileName = $_FILES['image'.$i]['name'];
if ($fileName){
try{
list($origWidth, $origHeight, $type) = getimagesize($_FILES['image'.$i]['tmp_name']);
$temp_name = "tempupload/".$fileName;
//make thumbnail to save in database
//resize the image to 200px and save as/in $temp_name (see resizeImage function)
resizeImage($_FILES['foto'.$i]['tmp_name'], $temp_name, 200, 200);
//retrieve saved image to put a watermark on it
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
$im2 = #imagecreatefromjpeg($temp_name);
break;
case 'image/png':
$im2 = #imagecreatefrompng($temp_name);
break;
}
//put watermark
$watermark = imagecreatefrompng('../assets/images/logo/watermark.png');
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($watermark);
$sy = imagesy($watermark);
imagecopy($im2, $watermark, imagesx($im2) - $sx - $marge_right, imagesy($im2) - $sy - $marge_bottom, 0, 0, imagesx($watermark), imagesy($watermark));
//save image with watermark
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
imagejpeg($im2, $temp_name);
break;
case 'image/png':
imagepng($im2, $temp_name);
break;
}
//open saved temp image
$saved_temp = fopen($temp_name,"rb");
//addslashes to image to save in database as BLOB
$image = addslashes(fread($saved_temp ,filesize($temp_name)));
fclose($saved_temp );
//End thumbnail
//Next part is to save the image in database in 1200px if user want this.
//this is used so that the user can download and use the image afterwards
$downloadimage="";
if(($_POST['image'.$i.'_Save']!="no") && ($_SESSION['package']!="A")){
//if width or height are smaller 700 us original width or height
$w = ($origWidth > 1200)?1200:$origWidth;
$h = ($origHeight > 1200)?1200:$origHeight;
if(($origWidth > 1200) || ($origHeight > 1200)){
//use same $temp_name to save memory????
resizeImage($_FILES['image'.$i]['tmp_name'], $temp_name, $w, $h,100);
}else{
//if image is to small, then move and save as $temp_name
move_uploaded_file($_FILES['image'.$i]["tmp_name"],$temp_name);
}
//put watermark
if(($_SESSION['package']=="B")){
// Get dimensions and type of $temp_name.
list($origWidth, $origHeight, $type) = getimagesize($temp_name);
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
$im2 = #imagecreatefromjpeg($temp_name);
break;
case 'image/png':
$im2 = #imagecreatefrompng($temp_name);
break;
}
imagecopy($im2, $watermark, imagesx($im2) - $sx - $marge_right, imagesy($im2) - $sy - $marge_bottom, 0, 0, imagesx($watermark), imagesy($watermark));
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
imagejpeg($im2, $temp_name);
break;
case 'image/png':
imagepng($im2, $temp_name);
break;
}
}
$saved_temp = fopen($temp_name,"rb");
$downloadimage = addslashes(fread($saved_temp ,filesize($temp_name)));
fclose($saved_temp );
}
//End making downloadimage
//SQL to save images in database
if(empty($downloadimage)){
$sql = "INSERT INTO tb_images(image,strange_id) VALUES (:image,:strange_id)";
$st = $conn->prepare($sql);
}else{
$sql = "INSERT INTO tb_images(image,strange_id,downloadimage,type) VALUES (:image,:strange_id,:downloadimage,:type)";
$st = $conn->prepare($sql);
$st->bindValue( ":downloadimage", $downloadimage, PDO::PARAM_LOB );
$st->bindValue( ":type", strtolower(image_type_to_mime_type($type)), PDO::PARAM_STR );
}
$st->bindValue( ":image", $image, PDO::PARAM_LOB );
$st->bindValue( ":strange_id", $strange_id, PDO::PARAM_INT );
$st->execute();
imagedestroy($watermark);
unlink($temp_name);
imagedestroy($im2);
}
catch (\Exception $e){
echo e;
}
}
}
the resize function
/**
* Resize image - preserve ratio of width and height.
* #param string $sourceImage path to source JPEG/PNG image
* #param string $targetImage path to final JPEG/PNG image file
* #param int $maxWidth maximum width of final image (value 0 - width is optional)
* #param int $maxHeight maximum height of final image (value 0 - height is optional)
* #param int $quality quality of final image (0-100)
* #return bool
*/
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80)
{
$isValid = #getimagesize($sourceImage);
if (!$isValid)
{
return false;
}
// Get dimensions and type of source image.
list($origWidth, $origHeight, $type) = getimagesize($sourceImage);
if ($maxWidth == 0)
{
$maxWidth = $origWidth;
}
if ($maxHeight == 0)
{
$maxHeight = $origHeight;
}
// Calculate ratio of desired maximum sizes and original sizes.
$widthRatio = $maxWidth / $origWidth;
$heightRatio = $maxHeight / $origHeight;
// Ratio used for calculating new image dimensions.
$ratio = min($widthRatio, $heightRatio);
// Calculate new image dimensions.
$newWidth = (int)$origWidth * $ratio;
$newHeight = (int)$origHeight * $ratio;
// Create final image with new dimensions.
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Obtain image from given source file.
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
$image = #imagecreatefromjpeg($sourceImage);
if (!$image)
{
return false;
}
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
if(imagejpeg($newImage,$targetImage,$quality))
{
// Free up the memory.
imagedestroy($image);
imagedestroy($newImage);
return true;
}
break;
case 'image/png':
$image = #imagecreatefrompng($sourceImage);
if (!$image)
{
return false;
}
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
if(imagepng($newImage,$targetImage, floor($quality / 10)))
{
// Free up the memory.
imagedestroy($image);
imagedestroy($newImage);
return true;
}
break;
default:
return false;
}
}

Oke... after much testing... this is the solution of my own problem :)
first of all this line...
resizeImage($_FILES['image'.$i]['tmp_name'], $temp_name, $w, $h,100);
Setting up quality 100% for PNG was a problem. I don't know why, but what I did is just replace this:
imagepng($newImage,$targetImage, floor($quality / 10))
with:
imagepng($newImage,$targetImage)
And I did it also for the JPEG.
Then the second problem was in my database. BLOB had to be LONG BLOB.
But now I am not storing the images in the database anymore. I am saving them in a folder. Not because of the LONG BLOB issue, but just because it is faster and less work to do.

Related

Crop Image using imagecopyresampled + Jcrop

I'm using Jcrop to crop images from the user. I followed the tutorial here: http://deepliquid.com/content/Jcrop_Implementation_Theory.html. Here's my code
private function resizeImage($file_info)
{
$dst_w = $dst_h = 150;
$jpeg_quality = 90;
$src = realpath($file_info['directory'] . '/' . $file_info['name']);
// CHMOD before cropping
chmod($src, 0777);
switch (strtolower($file_info['mime'])) {
case 'image/jpeg':
$src_img = imagecreatefromjpeg($src);
break;
case 'image/png':
$src_img = imagecreatefrompng($src);
break;
case 'image/gif':
$src_img = imagecreatefromgif($src);
break;
default:
exit('Unsupported type: ' . $file_info['mime']);
}
$dst_img = imagecreatetruecolor($dst_w, $dst_h);
// Resize and crop the image
imagecopyresampled(
$dst_img, $src_img, // Destination and Source image link resource
0, 0, // Coordinate of destination point
$this->crop['x'], $this->crop['y'], // Coordinate of source point
$dst_w, $dst_h, // Destination width and height
$this->crop['w'], $this->crop['h'] // Source width and height
);
// Output the image
switch (strtolower($file_info['mime'])) {
case 'image/jpeg':
imagejpeg($dst_img, null, $jpeg_quality);
break;
case 'image/png':
imagepng($dst_img);
break;
case 'image/gif':
imagegif($dst_img);
break;
default:
exit('Unsupported type: ' . $file_info['mime']);
}
}
I have checked both directory and file are writable (0777 permission). All variables I'm using are well-defined as well, nothing error. However, the final image is still in its original form, not cropped.
Anybody knows why it's not working? Any help is appreciated.
you're using list() to get the width and height of the source image, but you're not using it in your imagecopyresampled() call. Everything else looks fine as far as i can see, if that doesn't fix it the problem is probably somewhere else in the class.
here's my cropping method for reference, if it helps.
/**
* Crops the image to the given dimensions, at the given starting point
* defaults to the top left
* #param type $width
* #param type $height
* #param type $x
* #param type $y
*/
public function crop($new_width, $new_height, $x = 0, $y = 0){
$img = imagecrop($this->image, array(
"x" => $x,
"y" => $y,
"width" => $new_width,
"height" => $new_height
));
$this->height = $new_height;
$this->width = $new_width;
if(false !== $img) $this->image = $img;
else self::Error("Could not crop image.");
return $this;
}
resizing method, for reference..
/**
* resizes the image to the dimensions provided
* #param type $width (of canvas)
* #param type $height (of canvas)
*/
public function resize($width, $height){
// Resize the image
$thumb = imagecreatetruecolor($width, $height);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
imagecopyresampled($thumb, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
$this->image = $thumb;
$this->width = $width;
$this->height = $height;
return $this;
}

Scale Image Using PHP and Maintaining Aspect Ratio

Basically I want to upload an image (which i've sorted) and scale it down to certain constraints such as max width and height but maintain the aspect ratio of the original image.
I don't have Imagick installed on the server - otherwise this would be easy.
Any help is appreciated as always.
Thanks.
EDIT: I don't need the whole code or anything, just a push in the right direction would be fantastic.
Actually the accepted solution it is not the correct solution. The reason is simple: there will be cases when the ratio of the source image and the ratio of the destination image will be different. Any calculation should reflect this difference.
Please note the relevant lines from the example given on PHP.net website:
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
The full example may be found here:
http://php.net/manual/en/function.imagecopyresampled.php
There are other answers (with examples) on stackoverflow to similar questions (the same question formulated in a different manner) that suffer of the same problem.
Example:
Let's say we have an image of 1630 x 2400 pixels that we want to be auto resized keeping the aspect ratio to 160 x 240. Let's do some math taking the accepted solution:
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
height = 240
width = 1630 * ( 160/2400 ) = 1630 * 0.0666666666666667 = 108.6666666666667
108.6 x 240 it's not the correct solution.
The next solution proposed is the following:
if($old_x < $old_y)
{
$thumb_w = $old_x/$old_y*$newHeight;
$thumb_h = $newHeight;
}
height = 240;
width = 1630 / 2400 * 240 = 163
It is better (as it maintain the aspect ratio), but it exceeded the maximum accepted width.
Both fail.
We do the math according to the solution proposed by PHP.net:
width = 160
height = 160/(1630 / 2400) = 160/0.6791666666666667 = 235.5828220858896 (the else clause). 160 x 236 (rounded) is the correct answer.
I had written a peice of code like this for another project I've done. I've copied it below, might need a bit of tinkering! (It does required the GD library)
These are the parameters it needs:
$image_name - Name of the image which is uploaded
$new_width - Width of the resized photo (maximum)
$new_height - Height of the resized photo (maximum)
$uploadDir - Directory of the original image
$moveToDir - Directory to save the resized image
It will scale down or up an image to the maximum width or height
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' || $mime['mime']=='image/jpeg' || $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' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$result = imagejpeg($dst_img,$new_thumb_loc,80);
}
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
Formule is wrong for keeping aspect ratio.
It should be: original height / original width x new width = new height
function createThumbnail($imageName,$newWidth,$newHeight,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $imageName;
$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 = $newWidth;
$thumb_h = $old_y/$old_x*$newWidth;
}
if($old_x < $old_y)
{
$thumb_w = $old_x/$old_y*$newHeight;
$thumb_h = $newHeight;
}
if($old_x == $old_y)
{
$thumb_w = $newWidth;
$thumb_h = $newHeight;
}
$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 . $imageName;
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;
}
I was thinking about how to achieve this and i came with a pretty nice solution that works in any case...
Lets say you want to resize heavy images that users upload to your site but you need it to maintain the ratio. So i came up with this :
<?php
// File
$filename = 'test.jpg';
// Get sizes
list($width, $height) = getimagesize($filename);
//obtain ratio
$imageratio = $width/$height;
if($imageratio >= 1){
$newwidth = 600;
$newheight = 600 / $imageratio;
}
else{
$newidth = 400;
$newheight = 400 / $imageratio;
};
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width,
$height);
// Output
imagejpeg($thumb, "img/test.jpg");
imagedestroy();
?>
In this case if width is bigger than height, i wanted the width to be 600px and if the height was bigger than the width, i wanted the width to be 400px
<?php
Class ResizedImage
{
public $imgfile;
public $string = '';
public $new_width = 0;
public $new_height = 0;
public $angle = 0;
public $max_font_size = 1000;
public $cropped = false;//whether crop the original image if h or w > new h or w
public $font = 'fonts/arialbd.ttf';
private $img;
private $trans_colour;
private $orange;
private $white;
private $whitetr;
private $blacktr;
public function PrintAsBase64()
{
$this->SetImage();
ob_start();
imagepng($this->img);
$b64img = ob_get_contents();
ob_clean();
imagedestroy($this->img);
$b64img = base64_encode($b64img);
echo($b64img);
}
public function PrintAsImage()
{
$this->SetImage();
header('Content-type: image/png');
imagepng($this->img);
imagedestroy($this->img);
}
private function SetImage()
{
if ($this->imgfile == '') {$this->imgfile='NoImageAvailable.jpg';}
$this->img = imagecreatefromstring(file_get_contents($this->imgfile));
$this->trans_colour = imagecolorallocatealpha($this->img, 0, 0, 0, 127);
$this->orange = imagecolorallocate($this->img, 220, 210, 60);
$this->white = imagecolorallocate($this->img, 255,255, 255);
$this->whitetr = imagecolorallocatealpha($this->img, 255,255, 255, 95);
$this->blacktr = imagecolorallocatealpha($this->img, 0, 0, 0, 95);
if ((!$this->cropped) && ($this->string !=''))
{$this->watermarkimage();}
if (($this->new_height > 0) && ($this->new_width > 0)) {$this->ResizeImage();};
if (($this->cropped) && ($this->string !=''))
{$this->watermarkimage();}
imageAlphaBlending($this->img, true);
imageSaveAlpha($this->img, true);
}
////
private function ResizeImage()
{
# v_fact and h_fact are the factor by which the original vertical / horizontal
# image sizes should be multiplied to get the image to your target size.
$v_fact = $this->new_height / imagesy($this->img);//target_height / im_height;
$h_fact = $this->new_width / imagesx($this->img);//target_width / im_width;
# you want to resize the image by the same factor in both vertical
# and horizontal direction, so you need to pick the correct factor from
# v_fact / h_fact so that the largest (relative to target) of the new height/width
# equals the target height/width and the smallest is lower than the target.
# this is the lowest of the two factors
if($this->cropped)
{ $im_fact = max($v_fact, $h_fact); }
else
{ $im_fact = min($v_fact, $h_fact); }
$new_height = round(imagesy($this->img) * $im_fact);
$new_width = round(imagesx($this->img) * $im_fact);
$img2 = $this->img;
$this->img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($this->img, $img2, 0, 0, 0, 0, $new_width, $new_height, imagesx($img2), imagesy($img2));
$img2 = $this->img;
$this->img = imagecreatetruecolor($this->new_width, $this->new_height);
imagefill($this->img, 0, 0, $this->trans_colour);
$dstx = 0;
$dsty = 0;
if ($this->cropped)
{
if (imagesx($this->img) < imagesx($img2))
{ $dstx = round((imagesx($this->img)-imagesx($img2))/2); }
if (imagesy($this->img) < imagesy($img2))
{ $dsty = round((imagesy($this->img)-imagesy($img2))/2); }
}
else
{
if (imagesx($this->img) > imagesx($img2))
{ $dstx = round((imagesx($this->img)-imagesx($img2))/2); }
if (imagesy($this->img) > imagesy($img2))
{ $dsty = round((imagesy($this->img)-imagesy($img2))/2); }
}
imagecopy ( $this->img, $img2, $dstx, $dsty, 0, 0, imagesx($img2) , imagesy($img2));
imagedestroy($img2);
}
////
private function calculateTextBox($text,$fontFile,$fontSize,$fontAngle)
{
/************
simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top: coordinates you will pass to imagettftext
width, height: dimension of the image you have to create
*************/
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
return array(
"left" => abs($minX) - 1,
"top" => abs($minY) - 1,
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect );
}
private function watermarkimage($font_size=0)
{
if ($this->string == '')
{die('Watermark function call width empty string!');}
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
while ( ($box['width'] < imagesx($this->img)) && ($box['height'] < imagesy($this->img)) && ($font_size <= $this->max_font_size) )
{
$font_size++;
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
}
$font_size--;
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
$vcenter = round((imagesy($this->img) / 2) + ($box['height'] / 2));
$hcenter = round((imagesx($this->img) - $box['width']) / 2 );
imagettftext($this->img, $font_size, $this->angle, $hcenter, $vcenter, $this->blacktr, $this->font, $this->string);
imagettftext($this->img, $font_size, $this->angle, $hcenter+1, $vcenter-2, $this->whitetr, $this->font, $this->string);
}
}
?>
Also I have been using the accepted answer but it does not keep the ratio in some cases. I have found some good answers on the forum and have put them in together and finally created a Class which resizes an image. As extra function u can put a watermark text.
u can see what happens when choose to crop or not, if not a transparent area will be added to the new resized image.
This example is more than asked, but I think it is a good example.
I know you are looking for a divisor that will allow resize your image proportionally. Check this demo
How to get our divisor mathematically
lets assume our original image has width x and height y;
x=300 and y = 700
Maximum height and maximum width is 200;
First, we will check which dimension of the image is greater than the other.
Our height (y) is greater than width(x)
Secondly, we check if our height is greater than our maximum height.
For our case, our height is greater than the maximum height. In a case where it less that the maximum height, we set our new height to our original height.
Finally, we look for our divisor as shown below
if y is set to maximum height 200 and max-y=200;
y=max-y, that is
if y=max-y
what about
x=?
that is,
if 700 is resized to 200
what about 300?
700=200
300=?
new width = (200 (new height) * 300(width)) / 700 (height)
so our divisor is
divisor= new height (300) / height(700)
new width = divisor * width or width / (1/divisor)
and vice versa for the width if it greater than height
if ($width > $height) {
if($width < $max_width)
$newwidth = $width;
else
$newwidth = $max_width;
$divisor = $width / $newwidth;
$newheight = floor( $height / $divisor);
}
else {
if($height < $max_height)
$newheight = $height;
else
$newheight = $max_height;
$divisor = $height / $newheight;
$newwidth = floor( $width / $divisor );
}
See the full example and try it using the working demo .
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
This is my function to scale an image with save aspect ration for X, Y or both axes.
It's also scales an image for percent of it size.
Compatibe with PHP 5.4
/** Use X axis to scale image. */
define('IMAGES_SCALE_AXIS_X', 1);
/** Use Y axis to scale image. */
define('IMAGES_SCALE_AXIS_Y', 2);
/** Use both X and Y axes to calc image scale. */
define('IMAGES_SCALE_AXIS_BOTH', IMAGES_SCALE_AXIS_X ^ IMAGES_SCALE_AXIS_Y);
/** Compression rate for JPEG image format. */
define('JPEG_COMPRESSION_QUALITY', 90);
/** Compression rate for PNG image format. */
define('PNG_COMPRESSION_QUALITY', 9);
/**
* Scales an image with save aspect ration for X, Y or both axes.
*
* #param string $sourceFile Absolute path to source image.
* #param string $destinationFile Absolute path to scaled image.
* #param int|null $toWidth Maximum `width` of scaled image.
* #param int|null $toHeight Maximum `height` of scaled image.
* #param int|null $percent Percent of scale of the source image's size.
* #param int $scaleAxis Determines how of axis will be used to scale image.
*
* May take a value of {#link IMAGES_SCALE_AXIS_X}, {#link IMAGES_SCALE_AXIS_Y} or {#link IMAGES_SCALE_AXIS_BOTH}.
* #return bool True on success or False on failure.
*/
function scaleImage($sourceFile, $destinationFile, $toWidth = null, $toHeight = null, $percent = null, $scaleAxis = IMAGES_SCALE_AXIS_BOTH) {
$toWidth = (int)$toWidth;
$toHeight = (int)$toHeight;
$percent = (int)$percent;
$result = false;
if (($toWidth | $toHeight | $percent)
&& file_exists($sourceFile)
&& (file_exists(dirname($destinationFile)) || mkdir(dirname($destinationFile), 0777, true))) {
$mime = getimagesize($sourceFile);
if (in_array($mime['mime'], ['image/jpg', 'image/jpeg', 'image/pjpeg'])) {
$src_img = imagecreatefromjpeg($sourceFile);
} elseif ($mime['mime'] == 'image/png') {
$src_img = imagecreatefrompng($sourceFile);
}
$original_width = imagesx($src_img);
$original_height = imagesy($src_img);
if ($scaleAxis == IMAGES_SCALE_AXIS_BOTH) {
if (!($toWidth | $percent)) {
$scaleAxis = IMAGES_SCALE_AXIS_Y;
} elseif (!($toHeight | $percent)) {
$scaleAxis = IMAGES_SCALE_AXIS_X;
}
}
if ($scaleAxis == IMAGES_SCALE_AXIS_X && $toWidth) {
$scale_ratio = $original_width / $toWidth;
} elseif ($scaleAxis == IMAGES_SCALE_AXIS_Y && $toHeight) {
$scale_ratio = $original_height / $toHeight;
} elseif ($percent) {
$scale_ratio = 100 / $percent;
} else {
$scale_ratio_width = $original_width / $toWidth;
$scale_ratio_height = $original_height / $toHeight;
if ($original_width / $scale_ratio_width < $toWidth && $original_height / $scale_ratio_height < $toHeight) {
$scale_ratio = min($scale_ratio_width, $scale_ratio_height);
} else {
$scale_ratio = max($scale_ratio_width, $scale_ratio_height);
}
}
$scale_width = $original_width / $scale_ratio;
$scale_height = $original_height / $scale_ratio;
$dst_img = imagecreatetruecolor($scale_width, $scale_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $scale_width, $scale_height, $original_width, $original_height);
if (in_array($mime['mime'], ['image/jpg', 'image/jpeg', 'image/pjpeg'])) {
$result = imagejpeg($dst_img, $destinationFile, JPEG_COMPRESSION_QUALITY);
} elseif ($mime['mime'] == 'image/png') {
$result = imagepng($dst_img, $destinationFile, PNG_COMPRESSION_QUALITY);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
return $result;
}
Tests:
$sourceFile = '/source/file.jpg'; // Original size: 672x100
$destinationPath = '/destination/path/';
scaleImage($sourceFile, $destinationPath . 'file_original_size.jpg', 672, 100);
// Result: Image 672x100
scaleImage($sourceFile, $destinationPath . 'file_scaled_75_PERCENT.jpg', null, null, 75);
// Result: Image 504x75
scaleImage($sourceFile, $destinationPath . 'file_scaled_336_X.jpg', 336, null, null, IMAGES_SCALE_AXIS_X);
// Result: Image 336x50
scaleImage($sourceFile, $destinationPath . 'file_scaled_50_Y.jpg', null, 50, null, IMAGES_SCALE_AXIS_Y);
// Result: Image 336x50
scaleImage($sourceFile, $destinationPath . 'file_scaled_500x70_BOTH.jpg', 500, 70, null, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 470x70
scaleImage($sourceFile, $destinationPath . 'file_scaled_450x70_BOTH.jpg', 450, 70, null, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 450x66
scaleImage($sourceFile, $destinationPath . 'file_scaled_500x70_40_PERCENT_BOTH.jpg', 500, 70, 40, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 268x40
Here is a comprehensive application that I worked hard on it to include most common operations like scale up & scale down, thumbnail, preserve aspect ratio, convert file type, change quality/file size and more...
<?php
//##// Resize (and convert) image (Scale up & scale down, thumbnail, preserve aspect ratio) //##//
///////////////////////////////////////////////
///////////////// Begin.Setup /////////////////
// Source File:
$src_file = "/your/server/path/to/file.png";// png or jpg files only
// Resize Dimensions:
// leave blank for no size change (convert only)
// if you specify one dimension, the other dimension will be calculated according to the aspect ratio
// if you specify both dimensions system will take care of it depending on the actual image size
// $newWidth = 2000;
// $newHeight = 1500;
// Destination Path: (optional, if none: download image)
$dst_path = "/your/server/path/new/";
// Destination File Name: (Leave blank for same file name)
// $dst_name = 'image_name_only_no_extension';
// Destination File Type: (Leave blank for same file extension)
// $dst_type = 'png';
$dst_type = 'jpg';
// Reduce to 8bit - 256 colors (Very low quality but very small file & transparent PNG. Only for thumbnails!)
// $palette_8bit = true;
///////////////// End.Setup /////////////////
///////////////////////////////////////////////
if (!$dst_name){$dst_name = strtolower(pathinfo($src_file, PATHINFO_FILENAME));}
if (!$dst_type){$dst_type = strtolower(pathinfo($src_file, PATHINFO_EXTENSION));}
if ($palette_8bit){$dst_type = 'png';}
if ($dst_path){$dst_file = $dst_path . $dst_name . '.' . $dst_type;}
$mime = getimagesize($src_file);// Get image dimensions and type
// Destination File Parameters:
if ($dst_type == 'png'){
$dst_content = 'image/png';
$quality = 9;// All same quality! 0 too big file // 0(no comp.)-9 (php default: 6)
} elseif ($dst_type == 'jpg'){
$dst_content = 'image/jpg';
$quality = 85;// 30 Min. 60 Mid. 85 Cool. 90 Max. (100 Full) // 0-100 (php default: 75)
} else {
exit('Unknown Destination File Type');
}
// Source File Parameters:
if ($mime['mime']=='image/png'){$src_img = imagecreatefrompng($src_file);}
elseif ($mime['mime']=='image/jpg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/jpeg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/pjpeg'){$src_img = imagecreatefromjpeg($src_file);}
else {exit('Unknown Source File Type');}
// Define Dimensions:
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if ($newWidth AND $newHeight){
if($old_x > $old_y){
$new_x = $newWidth;
$new_y = $old_y / $old_x * $newWidth;
} elseif($old_x < $old_y){
$new_y = $newHeight;
$new_x = $old_x / $old_y * $newHeight;
} elseif($old_x == $old_y){
$new_x = $newWidth;
$new_y = $newHeight;
}
} elseif ($newWidth){
$new_x = $newWidth;
$new_y = $old_y / $old_x * $newWidth;
} elseif ($newHeight){
$new_y = $newHeight;
$new_x = $old_x / $old_y * $newHeight;
} else {
$new_x = $old_x;
$new_y = $old_y;
}
$dst_img = ImageCreateTrueColor($new_x, $new_y);
if ($palette_8bit){//////// Reduce to 8bit - 256 colors ////////
$transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
imagecolortransparent($dst_img, $transparent);
imagefill($dst_img, 0, 0, $transparent);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
imagetruecolortopalette($dst_img, false, 255);
imagesavealpha($dst_img, true);
} else {
// Check image and set transparent for png or white background for jpg
if ($dst_type == 'png'){
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
$transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $transparent);
} elseif ($dst_type == 'jpg'){
$white = imagecolorallocate($dst_img, 255, 255, 255);
imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $white);
}
imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
}
// Skip the save to parameter using NULL, then set the quality; imagejpeg($dst_img);=> Default quality
if ($dst_file){
if ($dst_type == 'png'){
imagepng($dst_img, $dst_file, $quality);
} elseif ($dst_type == 'jpg'){
imagejpeg($dst_img, $dst_file, $quality);
}
} else {
header('Content-Disposition: Attachment;filename=' . $dst_name . '.' . $dst_type);// comment this line to show image in browser instead of download
header('Content-type: ' . $dst_content);
if ($dst_type == 'png'){
imagepng($dst_img, NULL, $quality);
} elseif ($dst_type == 'jpg'){
imagejpeg($dst_img, NULL, $quality);
}
}
imagedestroy($src_img);
imagedestroy($dst_img);
//##// END : Resize image (Scale Up & Down) (thumbnail, bigger image, preserve aspect ratio) END //##//
works perfecly for me
static function getThumpnail($file){
$THUMBNAIL_IMAGE_MAX_WIDTH = 150; # exmpl.
$THUMBNAIL_IMAGE_MAX_HEIGHT = 150;
$src_size = filesize($file);
$filename = basename($file);
list($src_width, $src_height, $src_type) = getimagesize($file);
$src_im = false;
switch ($src_type) {
case IMAGETYPE_GIF : $src_im = imageCreateFromGif($file); break;
case IMAGETYPE_JPEG : $src_im = imageCreateFromJpeg($file); break;
case IMAGETYPE_PNG : $src_im = imageCreateFromPng($file); break;
case IMAGETYPE_WBMP : $src_im = imagecreatefromwbmp($file); break;
}
if ($src_im === false) { return false; }
$src_aspect_ratio = $src_width / $src_height;
$thu_aspect_ratio = $THUMBNAIL_IMAGE_MAX_WIDTH / $THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($src_width <= $THUMBNAIL_IMAGE_MAX_WIDTH && $src_height <= $THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thu_width = $src_width;
$thu_height = $src_height;
} elseif ($thu_aspect_ratio > $src_aspect_ratio) {
$thu_width = (int) ($THUMBNAIL_IMAGE_MAX_HEIGHT * $src_aspect_ratio);
$thu_height = $THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thu_width = $THUMBNAIL_IMAGE_MAX_WIDTH;
$thu_height = (int) ($THUMBNAIL_IMAGE_MAX_WIDTH / $src_aspect_ratio);
}
$thu_im = imagecreatetruecolor($thu_width, $thu_height);
imagecopyresampled($thu_im, $src_im, 0, 0, 0, 0, $thu_width, $thu_height, $src_width, $src_height);
$dst_im = imagecreatetruecolor($THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_WIDTH);
$backcolor = imagecolorallocate($dst_im,192,192,192);
imagefill($dst_im,0,0,$backcolor);
imagecopy($dst_im, $thu_im, (imagesx($dst_im)/2)-(imagesx($thu_im)/2), (imagesy($dst_im)/2)-(imagesy($thu_im)/2), 0, 0, imagesx($thu_im), imagesy($thu_im));
imagedestroy($src_im);
imagedestroy($thu_im);
}

PHP's imagepng() method saves an invalid image

I am using the GD library to automatically generate a thumbnail version of an uploaded image. I call the appropriate image____() function to save in the same format as the original. My code works fine for JPEG and GIF, but if I upload a PNG file, the resulting thumbnail is invalid. It actually only contains 33 bytes (with any source PNG that I've tried so far). This image does not display in the browser, nor can it be opened by Preview (on MacOS).
I use imagecreatetruecolor() along with imagecopyresampled() to generate the thumbnail, like this:
function _resizeImageToFit($resource, $size)
{
$sourceWidth = imagesx($resource);
$sourceHeight = imagesy($resource);
if($sourceWidth >= $sourceHeight) {
// landscape or square
$newHeight = 1.0*$size/$sourceWidth*$sourceHeight;
$newWidth = $size;
}
else {
// portrait
$newWidth = 1.0*$size/$sourceHeight*$sourceWidth;
$newHeight = $size;
}
$thmb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thmb, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
return $thmb;
}
Below is the version info of my setup (It's MAMP Version 1.9.4)
PHP Version 5.3.2
GD Version bundled (2.0.34 compatible)
Here is an example of an invalid generated thumbnail image (PNG):
âPNG
IHDRdaØMì∞
I found my error. imagepng() takes a quality value range of 0 to 9, while imagejpeg() takes a range of 0 to 100 and imagegif() doesn't take any such parameter. I was trying to save a PNG with a quality of 100.
So, this is a lovely case of RTM. Thanks for your responses.
http://ca3.php.net/manual/en/function.imagepng.php
http://ca3.php.net/manual/en/function.imagejpeg.php
http://ca3.php.net/manual/en/function.imagegif.php
Try this function.
/**
* Crop new images using the source image
*
* #param string $source - Image source
* #param string $destination - Image destination
* #param integer $thumbW - Width for the new image
* #param integer $thumbH - Height for the new image
* #param string $imageType - Type of the image
*
* #return bool
*/
function cropImage($source, $destination, $thumbW, $thumbH, $imageType)
{
list($width, $height, $type, $attr) = getimagesize($source);
$x = 0;
$y = 0;
if ($width*$thumbH>$height*$thumbW) {
$x = ceil(($width - $height*$thumbW/$thumbH)/2);
$width = $height*$thumbW/$thumbH;
} else {
$y = ceil(($height - $width*$thumbH/$thumbW)/2);
$height = $width*$thumbH/$thumbW;
}
$newImage = imagecreatetruecolor($thumbW, $thumbH) or die ('Can not use GD');
/*
if ($extension=='jpg' || $extension=='jpeg') {
$image = imagecreatefromjpeg($source);
} else if ($extension=='gif') {
$image = imagecreatefromgif($source);
} else if ($extension=='png') {
$image = imagecreatefrompng($source);
}
*/
switch($imageType) {
case "image/gif":
$image = imagecreatefromgif($source);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$image = imagecreatefromjpeg($source);
break;
case "image/png":
case "image/x-png":
$image = imagecreatefrompng($source);
break;
}
if (!#imagecopyresampled($newImage, $image, 0, 0, $x, $y, $thumbW, $thumbH, $width, $height)) {
return false;
} else {
imagejpeg($newImage, $destination,100);
imagedestroy($image);
return true;
}
}

Image resize PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can anybody suggest the best image resize script in php?
I'm still a newbie regarding image handling or file handling for that matter in PHP.
Would appreciate any input regarding the following
I post an image file using a simple html form and upload it via php.
When i try and alter my code to accomodate larger files (i.e. resize) I get an error.
Have been searching online but cant find anything really simple.
$size = getimagesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size == FALSE)
{
$errors=1;
}else if($size[0] > 300){ //if width greater than 300px
$aspectRatio = 300 / $size[0];
$newWidth = round($aspectRatio * $size[0]);
$newHeight = round($aspectRatio * $size[1]);
$imgHolder = imagecreatetruecolor($newWidth,$newHeight);
}
$newname= ROOTPATH.LOCALDIR."/images/".$image_name; //image_name is generated
$copy = imagecopyresized($imgHolder, $_FILES['image']['tmp_name'], 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
move_uploaded_file($copy, $newname); //where I want to move the file to the location of $newname
The error I get is:
imagecopyresized(): supplied argument
is not a valid Image resource in
Thanks in advance
Thanks for all your input, i've changed it to this
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$copy = imagecopyresized($imgHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
if(!move_uploaded_file($copy, $newname)){
$errors=1;
}
Not getting a PHP log error but its not saving :(
Any ideas?
Thanks again
Result
Following works.
$oldImage = imagecreatefromjpeg($img);
$imageHolder = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($imageHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($imageHolder, $newname, 100);
Thanks for everyones help
imagecopyresized takes an image resource as its second parameter, not a file name. You'll need to load the file first. If you know the file type, you can use imagecreatefromFILETYPE to load it. For example, if it's a JPEG, use imagecreatefromjpeg and pass that the file name - this will return an image resource.
If you don't know the file type, all is not lost. You can read the file in as a string and use imagecreatefromstring (which detects file types automatically) to load it as follows:
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$_FILES['image']['tmp_name'] is path not image resource. You have to use one of imagecreatefrom*() functions to create resource.
Here is my implementation of saving a thumbnail picture:
Resize and save function:
function SaveThumbnail($imagePath, $saveAs, $max_x, $max_y)
{
ini_set("memory_limit","32M");
$im = imagecreatefromjpeg ($imagePath);
$x = imagesx($im);
$y = imagesy($im);
if (($max_x/$max_y) < ($x/$y))
{
$save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
}
else
{
$save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
}
imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);
imagejpeg($save, $saveAs);
imagedestroy($im);
imagedestroy($save);
}
Usage:
$thumb_dir = "/path/to/thumbnaildir/"
$thumb_name = "thumb.jpg"
$muf = move_uploaded_file($_FILES['imgfile']['tmp_name'], "/tmp/test.jpg")
if($muf)
{
SaveThumbnail("/tmp/test.jpg", $thumb_dir . $thumb_name, 128, 128);
}
I use ImageMagick for stuff like that. Look how much simpler it is!
An example from one of my scripts:
$target= //destination path
move_uploaded_file($_FILES['item']['tmp_name'],$target);
$image = new imagick($target);
$image->setImageColorspace(imagick::COLORSPACE_RGB);
$image->scaleImage(350,0);
$image->writeImage($target);
You could then use getImageGeometry() to obtain the width and height.
For example:
$size=$image->getImageGeometry();
if($size['width'] > 300){ //if width greater than
$image->scaleImage(300,0);
}
Also, using scaleImage(300,0) means that ImageMagick automatically calculates the height based on the aspect ratio.
I was working on sth similar. I tried Ghostscript and ImageMagic. They are good tools but takes a but of time to set up. I ended up using 'sips' on a Snow Leopard server. Not sure if it's built in to Linux server but it's the faster solution I have found if you need sth done quick.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}

Image GD resize to 100px while keep the ratio [duplicate]

Basically I want to upload an image (which i've sorted) and scale it down to certain constraints such as max width and height but maintain the aspect ratio of the original image.
I don't have Imagick installed on the server - otherwise this would be easy.
Any help is appreciated as always.
Thanks.
EDIT: I don't need the whole code or anything, just a push in the right direction would be fantastic.
Actually the accepted solution it is not the correct solution. The reason is simple: there will be cases when the ratio of the source image and the ratio of the destination image will be different. Any calculation should reflect this difference.
Please note the relevant lines from the example given on PHP.net website:
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
The full example may be found here:
http://php.net/manual/en/function.imagecopyresampled.php
There are other answers (with examples) on stackoverflow to similar questions (the same question formulated in a different manner) that suffer of the same problem.
Example:
Let's say we have an image of 1630 x 2400 pixels that we want to be auto resized keeping the aspect ratio to 160 x 240. Let's do some math taking the accepted solution:
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
height = 240
width = 1630 * ( 160/2400 ) = 1630 * 0.0666666666666667 = 108.6666666666667
108.6 x 240 it's not the correct solution.
The next solution proposed is the following:
if($old_x < $old_y)
{
$thumb_w = $old_x/$old_y*$newHeight;
$thumb_h = $newHeight;
}
height = 240;
width = 1630 / 2400 * 240 = 163
It is better (as it maintain the aspect ratio), but it exceeded the maximum accepted width.
Both fail.
We do the math according to the solution proposed by PHP.net:
width = 160
height = 160/(1630 / 2400) = 160/0.6791666666666667 = 235.5828220858896 (the else clause). 160 x 236 (rounded) is the correct answer.
I had written a peice of code like this for another project I've done. I've copied it below, might need a bit of tinkering! (It does required the GD library)
These are the parameters it needs:
$image_name - Name of the image which is uploaded
$new_width - Width of the resized photo (maximum)
$new_height - Height of the resized photo (maximum)
$uploadDir - Directory of the original image
$moveToDir - Directory to save the resized image
It will scale down or up an image to the maximum width or height
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' || $mime['mime']=='image/jpeg' || $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' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$result = imagejpeg($dst_img,$new_thumb_loc,80);
}
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
Formule is wrong for keeping aspect ratio.
It should be: original height / original width x new width = new height
function createThumbnail($imageName,$newWidth,$newHeight,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $imageName;
$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 = $newWidth;
$thumb_h = $old_y/$old_x*$newWidth;
}
if($old_x < $old_y)
{
$thumb_w = $old_x/$old_y*$newHeight;
$thumb_h = $newHeight;
}
if($old_x == $old_y)
{
$thumb_w = $newWidth;
$thumb_h = $newHeight;
}
$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 . $imageName;
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;
}
I was thinking about how to achieve this and i came with a pretty nice solution that works in any case...
Lets say you want to resize heavy images that users upload to your site but you need it to maintain the ratio. So i came up with this :
<?php
// File
$filename = 'test.jpg';
// Get sizes
list($width, $height) = getimagesize($filename);
//obtain ratio
$imageratio = $width/$height;
if($imageratio >= 1){
$newwidth = 600;
$newheight = 600 / $imageratio;
}
else{
$newidth = 400;
$newheight = 400 / $imageratio;
};
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width,
$height);
// Output
imagejpeg($thumb, "img/test.jpg");
imagedestroy();
?>
In this case if width is bigger than height, i wanted the width to be 600px and if the height was bigger than the width, i wanted the width to be 400px
<?php
Class ResizedImage
{
public $imgfile;
public $string = '';
public $new_width = 0;
public $new_height = 0;
public $angle = 0;
public $max_font_size = 1000;
public $cropped = false;//whether crop the original image if h or w > new h or w
public $font = 'fonts/arialbd.ttf';
private $img;
private $trans_colour;
private $orange;
private $white;
private $whitetr;
private $blacktr;
public function PrintAsBase64()
{
$this->SetImage();
ob_start();
imagepng($this->img);
$b64img = ob_get_contents();
ob_clean();
imagedestroy($this->img);
$b64img = base64_encode($b64img);
echo($b64img);
}
public function PrintAsImage()
{
$this->SetImage();
header('Content-type: image/png');
imagepng($this->img);
imagedestroy($this->img);
}
private function SetImage()
{
if ($this->imgfile == '') {$this->imgfile='NoImageAvailable.jpg';}
$this->img = imagecreatefromstring(file_get_contents($this->imgfile));
$this->trans_colour = imagecolorallocatealpha($this->img, 0, 0, 0, 127);
$this->orange = imagecolorallocate($this->img, 220, 210, 60);
$this->white = imagecolorallocate($this->img, 255,255, 255);
$this->whitetr = imagecolorallocatealpha($this->img, 255,255, 255, 95);
$this->blacktr = imagecolorallocatealpha($this->img, 0, 0, 0, 95);
if ((!$this->cropped) && ($this->string !=''))
{$this->watermarkimage();}
if (($this->new_height > 0) && ($this->new_width > 0)) {$this->ResizeImage();};
if (($this->cropped) && ($this->string !=''))
{$this->watermarkimage();}
imageAlphaBlending($this->img, true);
imageSaveAlpha($this->img, true);
}
////
private function ResizeImage()
{
# v_fact and h_fact are the factor by which the original vertical / horizontal
# image sizes should be multiplied to get the image to your target size.
$v_fact = $this->new_height / imagesy($this->img);//target_height / im_height;
$h_fact = $this->new_width / imagesx($this->img);//target_width / im_width;
# you want to resize the image by the same factor in both vertical
# and horizontal direction, so you need to pick the correct factor from
# v_fact / h_fact so that the largest (relative to target) of the new height/width
# equals the target height/width and the smallest is lower than the target.
# this is the lowest of the two factors
if($this->cropped)
{ $im_fact = max($v_fact, $h_fact); }
else
{ $im_fact = min($v_fact, $h_fact); }
$new_height = round(imagesy($this->img) * $im_fact);
$new_width = round(imagesx($this->img) * $im_fact);
$img2 = $this->img;
$this->img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($this->img, $img2, 0, 0, 0, 0, $new_width, $new_height, imagesx($img2), imagesy($img2));
$img2 = $this->img;
$this->img = imagecreatetruecolor($this->new_width, $this->new_height);
imagefill($this->img, 0, 0, $this->trans_colour);
$dstx = 0;
$dsty = 0;
if ($this->cropped)
{
if (imagesx($this->img) < imagesx($img2))
{ $dstx = round((imagesx($this->img)-imagesx($img2))/2); }
if (imagesy($this->img) < imagesy($img2))
{ $dsty = round((imagesy($this->img)-imagesy($img2))/2); }
}
else
{
if (imagesx($this->img) > imagesx($img2))
{ $dstx = round((imagesx($this->img)-imagesx($img2))/2); }
if (imagesy($this->img) > imagesy($img2))
{ $dsty = round((imagesy($this->img)-imagesy($img2))/2); }
}
imagecopy ( $this->img, $img2, $dstx, $dsty, 0, 0, imagesx($img2) , imagesy($img2));
imagedestroy($img2);
}
////
private function calculateTextBox($text,$fontFile,$fontSize,$fontAngle)
{
/************
simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top: coordinates you will pass to imagettftext
width, height: dimension of the image you have to create
*************/
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
return array(
"left" => abs($minX) - 1,
"top" => abs($minY) - 1,
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect );
}
private function watermarkimage($font_size=0)
{
if ($this->string == '')
{die('Watermark function call width empty string!');}
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
while ( ($box['width'] < imagesx($this->img)) && ($box['height'] < imagesy($this->img)) && ($font_size <= $this->max_font_size) )
{
$font_size++;
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
}
$font_size--;
$box = $this->calculateTextBox($this->string, $this->font, $font_size, $this->angle);
$vcenter = round((imagesy($this->img) / 2) + ($box['height'] / 2));
$hcenter = round((imagesx($this->img) - $box['width']) / 2 );
imagettftext($this->img, $font_size, $this->angle, $hcenter, $vcenter, $this->blacktr, $this->font, $this->string);
imagettftext($this->img, $font_size, $this->angle, $hcenter+1, $vcenter-2, $this->whitetr, $this->font, $this->string);
}
}
?>
Also I have been using the accepted answer but it does not keep the ratio in some cases. I have found some good answers on the forum and have put them in together and finally created a Class which resizes an image. As extra function u can put a watermark text.
u can see what happens when choose to crop or not, if not a transparent area will be added to the new resized image.
This example is more than asked, but I think it is a good example.
I know you are looking for a divisor that will allow resize your image proportionally. Check this demo
How to get our divisor mathematically
lets assume our original image has width x and height y;
x=300 and y = 700
Maximum height and maximum width is 200;
First, we will check which dimension of the image is greater than the other.
Our height (y) is greater than width(x)
Secondly, we check if our height is greater than our maximum height.
For our case, our height is greater than the maximum height. In a case where it less that the maximum height, we set our new height to our original height.
Finally, we look for our divisor as shown below
if y is set to maximum height 200 and max-y=200;
y=max-y, that is
if y=max-y
what about
x=?
that is,
if 700 is resized to 200
what about 300?
700=200
300=?
new width = (200 (new height) * 300(width)) / 700 (height)
so our divisor is
divisor= new height (300) / height(700)
new width = divisor * width or width / (1/divisor)
and vice versa for the width if it greater than height
if ($width > $height) {
if($width < $max_width)
$newwidth = $width;
else
$newwidth = $max_width;
$divisor = $width / $newwidth;
$newheight = floor( $height / $divisor);
}
else {
if($height < $max_height)
$newheight = $height;
else
$newheight = $max_height;
$divisor = $height / $newheight;
$newwidth = floor( $width / $divisor );
}
See the full example and try it using the working demo .
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
This is my function to scale an image with save aspect ration for X, Y or both axes.
It's also scales an image for percent of it size.
Compatibe with PHP 5.4
/** Use X axis to scale image. */
define('IMAGES_SCALE_AXIS_X', 1);
/** Use Y axis to scale image. */
define('IMAGES_SCALE_AXIS_Y', 2);
/** Use both X and Y axes to calc image scale. */
define('IMAGES_SCALE_AXIS_BOTH', IMAGES_SCALE_AXIS_X ^ IMAGES_SCALE_AXIS_Y);
/** Compression rate for JPEG image format. */
define('JPEG_COMPRESSION_QUALITY', 90);
/** Compression rate for PNG image format. */
define('PNG_COMPRESSION_QUALITY', 9);
/**
* Scales an image with save aspect ration for X, Y or both axes.
*
* #param string $sourceFile Absolute path to source image.
* #param string $destinationFile Absolute path to scaled image.
* #param int|null $toWidth Maximum `width` of scaled image.
* #param int|null $toHeight Maximum `height` of scaled image.
* #param int|null $percent Percent of scale of the source image's size.
* #param int $scaleAxis Determines how of axis will be used to scale image.
*
* May take a value of {#link IMAGES_SCALE_AXIS_X}, {#link IMAGES_SCALE_AXIS_Y} or {#link IMAGES_SCALE_AXIS_BOTH}.
* #return bool True on success or False on failure.
*/
function scaleImage($sourceFile, $destinationFile, $toWidth = null, $toHeight = null, $percent = null, $scaleAxis = IMAGES_SCALE_AXIS_BOTH) {
$toWidth = (int)$toWidth;
$toHeight = (int)$toHeight;
$percent = (int)$percent;
$result = false;
if (($toWidth | $toHeight | $percent)
&& file_exists($sourceFile)
&& (file_exists(dirname($destinationFile)) || mkdir(dirname($destinationFile), 0777, true))) {
$mime = getimagesize($sourceFile);
if (in_array($mime['mime'], ['image/jpg', 'image/jpeg', 'image/pjpeg'])) {
$src_img = imagecreatefromjpeg($sourceFile);
} elseif ($mime['mime'] == 'image/png') {
$src_img = imagecreatefrompng($sourceFile);
}
$original_width = imagesx($src_img);
$original_height = imagesy($src_img);
if ($scaleAxis == IMAGES_SCALE_AXIS_BOTH) {
if (!($toWidth | $percent)) {
$scaleAxis = IMAGES_SCALE_AXIS_Y;
} elseif (!($toHeight | $percent)) {
$scaleAxis = IMAGES_SCALE_AXIS_X;
}
}
if ($scaleAxis == IMAGES_SCALE_AXIS_X && $toWidth) {
$scale_ratio = $original_width / $toWidth;
} elseif ($scaleAxis == IMAGES_SCALE_AXIS_Y && $toHeight) {
$scale_ratio = $original_height / $toHeight;
} elseif ($percent) {
$scale_ratio = 100 / $percent;
} else {
$scale_ratio_width = $original_width / $toWidth;
$scale_ratio_height = $original_height / $toHeight;
if ($original_width / $scale_ratio_width < $toWidth && $original_height / $scale_ratio_height < $toHeight) {
$scale_ratio = min($scale_ratio_width, $scale_ratio_height);
} else {
$scale_ratio = max($scale_ratio_width, $scale_ratio_height);
}
}
$scale_width = $original_width / $scale_ratio;
$scale_height = $original_height / $scale_ratio;
$dst_img = imagecreatetruecolor($scale_width, $scale_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $scale_width, $scale_height, $original_width, $original_height);
if (in_array($mime['mime'], ['image/jpg', 'image/jpeg', 'image/pjpeg'])) {
$result = imagejpeg($dst_img, $destinationFile, JPEG_COMPRESSION_QUALITY);
} elseif ($mime['mime'] == 'image/png') {
$result = imagepng($dst_img, $destinationFile, PNG_COMPRESSION_QUALITY);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
return $result;
}
Tests:
$sourceFile = '/source/file.jpg'; // Original size: 672x100
$destinationPath = '/destination/path/';
scaleImage($sourceFile, $destinationPath . 'file_original_size.jpg', 672, 100);
// Result: Image 672x100
scaleImage($sourceFile, $destinationPath . 'file_scaled_75_PERCENT.jpg', null, null, 75);
// Result: Image 504x75
scaleImage($sourceFile, $destinationPath . 'file_scaled_336_X.jpg', 336, null, null, IMAGES_SCALE_AXIS_X);
// Result: Image 336x50
scaleImage($sourceFile, $destinationPath . 'file_scaled_50_Y.jpg', null, 50, null, IMAGES_SCALE_AXIS_Y);
// Result: Image 336x50
scaleImage($sourceFile, $destinationPath . 'file_scaled_500x70_BOTH.jpg', 500, 70, null, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 470x70
scaleImage($sourceFile, $destinationPath . 'file_scaled_450x70_BOTH.jpg', 450, 70, null, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 450x66
scaleImage($sourceFile, $destinationPath . 'file_scaled_500x70_40_PERCENT_BOTH.jpg', 500, 70, 40, IMAGES_SCALE_AXIS_BOTH);
// Result: Image 268x40
Here is a comprehensive application that I worked hard on it to include most common operations like scale up & scale down, thumbnail, preserve aspect ratio, convert file type, change quality/file size and more...
<?php
//##// Resize (and convert) image (Scale up & scale down, thumbnail, preserve aspect ratio) //##//
///////////////////////////////////////////////
///////////////// Begin.Setup /////////////////
// Source File:
$src_file = "/your/server/path/to/file.png";// png or jpg files only
// Resize Dimensions:
// leave blank for no size change (convert only)
// if you specify one dimension, the other dimension will be calculated according to the aspect ratio
// if you specify both dimensions system will take care of it depending on the actual image size
// $newWidth = 2000;
// $newHeight = 1500;
// Destination Path: (optional, if none: download image)
$dst_path = "/your/server/path/new/";
// Destination File Name: (Leave blank for same file name)
// $dst_name = 'image_name_only_no_extension';
// Destination File Type: (Leave blank for same file extension)
// $dst_type = 'png';
$dst_type = 'jpg';
// Reduce to 8bit - 256 colors (Very low quality but very small file & transparent PNG. Only for thumbnails!)
// $palette_8bit = true;
///////////////// End.Setup /////////////////
///////////////////////////////////////////////
if (!$dst_name){$dst_name = strtolower(pathinfo($src_file, PATHINFO_FILENAME));}
if (!$dst_type){$dst_type = strtolower(pathinfo($src_file, PATHINFO_EXTENSION));}
if ($palette_8bit){$dst_type = 'png';}
if ($dst_path){$dst_file = $dst_path . $dst_name . '.' . $dst_type;}
$mime = getimagesize($src_file);// Get image dimensions and type
// Destination File Parameters:
if ($dst_type == 'png'){
$dst_content = 'image/png';
$quality = 9;// All same quality! 0 too big file // 0(no comp.)-9 (php default: 6)
} elseif ($dst_type == 'jpg'){
$dst_content = 'image/jpg';
$quality = 85;// 30 Min. 60 Mid. 85 Cool. 90 Max. (100 Full) // 0-100 (php default: 75)
} else {
exit('Unknown Destination File Type');
}
// Source File Parameters:
if ($mime['mime']=='image/png'){$src_img = imagecreatefrompng($src_file);}
elseif ($mime['mime']=='image/jpg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/jpeg'){$src_img = imagecreatefromjpeg($src_file);}
elseif ($mime['mime']=='image/pjpeg'){$src_img = imagecreatefromjpeg($src_file);}
else {exit('Unknown Source File Type');}
// Define Dimensions:
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if ($newWidth AND $newHeight){
if($old_x > $old_y){
$new_x = $newWidth;
$new_y = $old_y / $old_x * $newWidth;
} elseif($old_x < $old_y){
$new_y = $newHeight;
$new_x = $old_x / $old_y * $newHeight;
} elseif($old_x == $old_y){
$new_x = $newWidth;
$new_y = $newHeight;
}
} elseif ($newWidth){
$new_x = $newWidth;
$new_y = $old_y / $old_x * $newWidth;
} elseif ($newHeight){
$new_y = $newHeight;
$new_x = $old_x / $old_y * $newHeight;
} else {
$new_x = $old_x;
$new_y = $old_y;
}
$dst_img = ImageCreateTrueColor($new_x, $new_y);
if ($palette_8bit){//////// Reduce to 8bit - 256 colors ////////
$transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
imagecolortransparent($dst_img, $transparent);
imagefill($dst_img, 0, 0, $transparent);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
imagetruecolortopalette($dst_img, false, 255);
imagesavealpha($dst_img, true);
} else {
// Check image and set transparent for png or white background for jpg
if ($dst_type == 'png'){
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
$transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $transparent);
} elseif ($dst_type == 'jpg'){
$white = imagecolorallocate($dst_img, 255, 255, 255);
imagefilledrectangle($dst_img, 0, 0, $new_x, $new_y, $white);
}
imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_x,$new_y,$old_x,$old_y);// Great quality resize.
}
// Skip the save to parameter using NULL, then set the quality; imagejpeg($dst_img);=> Default quality
if ($dst_file){
if ($dst_type == 'png'){
imagepng($dst_img, $dst_file, $quality);
} elseif ($dst_type == 'jpg'){
imagejpeg($dst_img, $dst_file, $quality);
}
} else {
header('Content-Disposition: Attachment;filename=' . $dst_name . '.' . $dst_type);// comment this line to show image in browser instead of download
header('Content-type: ' . $dst_content);
if ($dst_type == 'png'){
imagepng($dst_img, NULL, $quality);
} elseif ($dst_type == 'jpg'){
imagejpeg($dst_img, NULL, $quality);
}
}
imagedestroy($src_img);
imagedestroy($dst_img);
//##// END : Resize image (Scale Up & Down) (thumbnail, bigger image, preserve aspect ratio) END //##//
works perfecly for me
static function getThumpnail($file){
$THUMBNAIL_IMAGE_MAX_WIDTH = 150; # exmpl.
$THUMBNAIL_IMAGE_MAX_HEIGHT = 150;
$src_size = filesize($file);
$filename = basename($file);
list($src_width, $src_height, $src_type) = getimagesize($file);
$src_im = false;
switch ($src_type) {
case IMAGETYPE_GIF : $src_im = imageCreateFromGif($file); break;
case IMAGETYPE_JPEG : $src_im = imageCreateFromJpeg($file); break;
case IMAGETYPE_PNG : $src_im = imageCreateFromPng($file); break;
case IMAGETYPE_WBMP : $src_im = imagecreatefromwbmp($file); break;
}
if ($src_im === false) { return false; }
$src_aspect_ratio = $src_width / $src_height;
$thu_aspect_ratio = $THUMBNAIL_IMAGE_MAX_WIDTH / $THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($src_width <= $THUMBNAIL_IMAGE_MAX_WIDTH && $src_height <= $THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thu_width = $src_width;
$thu_height = $src_height;
} elseif ($thu_aspect_ratio > $src_aspect_ratio) {
$thu_width = (int) ($THUMBNAIL_IMAGE_MAX_HEIGHT * $src_aspect_ratio);
$thu_height = $THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thu_width = $THUMBNAIL_IMAGE_MAX_WIDTH;
$thu_height = (int) ($THUMBNAIL_IMAGE_MAX_WIDTH / $src_aspect_ratio);
}
$thu_im = imagecreatetruecolor($thu_width, $thu_height);
imagecopyresampled($thu_im, $src_im, 0, 0, 0, 0, $thu_width, $thu_height, $src_width, $src_height);
$dst_im = imagecreatetruecolor($THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_WIDTH);
$backcolor = imagecolorallocate($dst_im,192,192,192);
imagefill($dst_im,0,0,$backcolor);
imagecopy($dst_im, $thu_im, (imagesx($dst_im)/2)-(imagesx($thu_im)/2), (imagesy($dst_im)/2)-(imagesy($thu_im)/2), 0, 0, imagesx($thu_im), imagesy($thu_im));
imagedestroy($src_im);
imagedestroy($thu_im);
}

Categories