Creating jpg thumb with php - php

I am having problems creating a thumbnail from an uploaded image, my problem is
(i) the quality
(ii) the crop
http://welovethedesign.com.cluster.cwcs.co.uk/phpimages/large.jpg
http://welovethedesign.com.cluster.cwcs.co.uk/phpimages/thumb.jpg
If you look the quality is very poor and the crop is taken from the top and is not a resize of the original image although the dimesions mean it is in proportion.
The original is 1600px wide by 1100px high.
Any help would be appreciated.
$thumb =
$targetPath."Thumbs/".$fileName;
$imgsize =
getimagesize($targetFile); $image =
imagecreatefromjpeg($targetFile);
$width = 200; //New width of image
$height = 138; //This maintains
proportions
$src_w = $imgsize[0]; $src_h =
$imgsize[1];
$thumbWidth = 200; $thumbHeight =
138; // Intended dimension of thumb
// Beyond this point is simply code.
$sourceImage =
imagecreatefromjpeg($targetFile);
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);
$targetImage =
imagecreate($thumbWidth,$thumbHeight);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
//imagejpeg($targetImage,
"$thumbPath/$thumbName");
imagejpeg($targetImage, $thumb);
chmod($thumb, 0755);

Every time u create a thumbnail the DPI of the image has to go low and thus it is not possible to have the same quality, however u can check imagecreatetruecolor (http://in2.php.net/manual/en/function.imagecreatetruecolor.php ) for improvement

You're using the wrong variable for the image height.
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
Should be:
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage));
This should improve image quality but you should use imagecopyresampled for resizing and use the quality parameter when using the imagejpeg() function when saving to disk.

You would not worry if you would use the Thumbnailer.
$th=new Thumbnailer("your-photo.jpg");
$th->thumbSymmetricWidth(200)->save("your-thumb.jpg");
The quality is superb. You can also round the corners.

Related

what is the right way to scale down an image in php

why is scaling image in php so complicated ? A lot of confusin about
imagecreatetruecolor
imagecreatefromjpeg
imagecopyresampled
imagejpeg - and so on
I simply want to scale down an image - if it's width is over 960px
something like this:
$path = "sbar/01.jpg";
$w = getimagesize($path)[0];
if($w > 960){scale($path, 960, auto);}
what is the simplest way to do this ? Here is my try:
$max = 960;
$h = getimagesize($path)[1];
$ratio = $w/$h;
$new_height = $w/$ratio;
$img = imagecreatetruecolor($max, $new_height);
$image = imagecreatefromjpeg($path);
And what now? There is still no desired image (960 x auto) in $path
There is no "best" way to do it. There are just different ways to do it. If you have an image that is already stored and you want to scale it and then save the scaled version you can simply do this:
$image = imagecreatefromjpeg('test.jpg');
$newImage = imagescale($image, 960, -1);
imagejpeg($newImage, 'scaled_image.jpg');
You first load the image from a given path. Then you scale it (while the image stays in memory). At the end, you save it under the provided path. Done.
The -1 (or if you omit the value altogether) means to only scale the other dimension and keep the aspect ratio.

Create fixed thumbnail dimensions for images with different sizes

I just want to know if it is possible to get different images' sizes, and create fixed thumbnail dimension measurements for these pictures without losing their accurate aspect ratios.
So far, I have made these:
Resize different images
Maintain their aspect ratios
NOT supplying the same size (for example: 100px- height and 100px- width)
Here's the code that I am working with:
<?php
require("dbinfo.php");
$allPhotosQuery = mysql_query (" SELECT * FROM `placesImages` ");
while ($allPhotosArray = mysql_fetch_assoc ($allPhotosQuery))
{
$filename= $allPhotosArray['fileName'];
$placeId = $allPhotosArray['placeId'];
$imagePath = "placesImages/" . $placeId . "/" . $filename;
$imageSize = getimagesize($imagePath);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$newSize = ($imageWidth + $imageHeight)/($imageWidth*($imageHeight/45));
$newHeight = $imageHeight * $newSize;
$newWidth = $imageWidth * $newSize;
echo "<img src='".$imagePath."' width='".$newWidth."' height='".$newHeight."' />";
}
?>
Short of cropping, the simplest way to maintain aspect ratio while making a thumbnail is to do something similar to what you have, but set one fixed:
For example, if you want all your tumbs to be 100px wide:
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$ratio=ImageWidth/$imageHeight;
$newHeight=(int)$ratio*100;
$newWidth=100;
The caveat with this is that you might end up with some funny sizes if the image has a funny ratio - as in it will happily go ahead and just do it. It might be a good idea to put some sort of check on the ratio in your code - if it it too low or too high, do something else, otherwise use this standard process.
feed this function your original image width and heights followed by the maximum constraints of your thumbnail limits and it will spit out an array with x/y of what you should set your thumbnail at to maintain aspect ratio. (anything smaller than the thumbnail will be enlarged)
function imageResizeDimensions($source_width,$source_height,$thumb_width,$thumb_height)
{
$source_ratio = $source_width / $source_height;
$thumb_ratio = $thumb_width / $thumb_height;
if($thumb_ratio > $source_ratio)
{
return array('x'=>$thumb_height * $source_ratio,'y'=>$thumb_height);
}
elseif($thumb_ratio < $source_ratio)
{
return array('x'=>$thumb_width,'y'=>$thumb_width/$source_ratio);
}
else
{
return array('x'=>$thumb_width,'y'=>$thumb_width);
}
}
Let’s begin with two constants, thumb_width and thumb_height, which are the desired width and height of your thumbnail images. They can be equal, but don’t have to be.
If you have an image that’s wider than it is tall (landscape) we can set the width to the desired width of the thumbnail, thumb_width, and adjust the height to maintain the aspect ratio.
new_width = thumb_width
new_height = thumb_height * old_height / old_width
See imagecreatetruecolor.
Then you can move the image to center it vertically within the limits of the thumbnail, producing a letterbox effect. See imagecopyresampled.
new_y = (thumb_height - new_height) / 2
For images that are taller than they are wide (portrait) the procedure is the same, but the math is a little different.
new_height = thumb_height
new_width = thumb_width * old_width / old_height
Then you can center it horizontally within the limits of the thumbnail.
new_x = (thumb_width - new_width) / 2
For more information on the basics of creating thumbnail images see Resizing images in PHP with GD and Imagick

How to restrict image width or height on upload

I would like manipulate/resize images in a similar way to Pinterest but I am not sure what is the best way to approach it. The goal is to allow a mix of both portrait and landscape images but put some restrictions on the maximum height and width.
The problem i can see is that if I resize to a width, a portrait image may become too thin, and the opposite it true for a landscape image.
Any ideas on how to achieve those sort of results with PHP?
You just need to understand which of the two edges of the image is longer, and compute the other dimension proportionally. If the maximum long-egde is 1024, then if one of the two edges is larger you will set that to 1024, and compute the other to fit the proportions. Then you will pass those two values to your image management functions.
Like here:
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
Or here:
http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html
try with this
$needheight = 1000;
$needwidth = 1000;
$arrtest = getimagesize($upload_image_physical_path);
$actualwidth = $arrtest[0];
$actualheight = $arrtest[1];
if($needwidth > $actualwidth || $needheight > $actualheight){
//uplaod code
}
cheers
Check for a max size and then resize based on a ratio. Here's a pseudo code example:
if($imageHeight > $maxHeight) {
$newHeight = $maxHeight;
$newWidth = $imageWidth * ($maxHeight / $imageHeight);
}
if($imageWidth > $maxWidth) {
$newWidth = $maxWidth;
$newHeight = $imageHeight * ($maxWidth / $imageWidth);
}
resize($image, $newWidth, $newHeight);
It first checks the height and if the height is greater, it scales it down. Then it checks the width. If the width is too big, it scales it down again. The end result, both height and width will be with in your bounds. It uses the ratio to do the scaling.
Note, this is pseudocodish. The actual resize function call will depend on your image manipulation library -- same goes for calls to obtain image size.

php: create custom-sized thumbnail

i'm familiar with resizing and cropping images under php using imagecopyresampled but now i'm having a special problem:
the task is cropping a large image from eg. 1600x1200 to 500x120, which means resizing down to 500px and crop its height that it'S 120px. is there some easy way or do i need to calculate the cropping values all on my own? thanks
There is PHP library that could help you out called PHPThumb. You can find here https://github.com/masterexploder/PHPThumb
They have an adaptive resize method that does what you're looking for. https://github.com/masterexploder/PHPThumb/wiki/Basic-Usage
You have to do it yourself.
I don't know if you want to crop or not, so here's how to calculate the values for both:
Scale image: resize to fit within new w x h keeping aspect ratio (so 1 side may be shorter than specified)
function calc_scale_dims($width_orig, $height_orig, $max_width, $max_height) {
$new_width=$width_orig;
$new_height=$height_orig;
$ratioh = $max_height/$new_height;
$ratiow = $max_width/$new_width;
$ratio = min($ratioh, $ratiow);
// New dimensions
$dims["w"] = intval($ratio*$new_width);
$dims["h"] = intval($ratio*$new_height);
return $dims;
}
Resize and Crop: Resizes image and crops it to fit into the specified w x h if new aspect ratio is different (e.g. if aspect ratios are different, image will be resized to match specified size on the short size and the longer size if cropped in the middle)
function calc_crop_resize_dims($width_orig, $height_orig, $new_width, $new_height) {
//Calculate scaling
$ratio_orig = $width_orig/$height_orig;
$ratio_new = $new_width/$new_height;
if ($ratio_new < $ratio_orig) {
$copy_width = $height_orig*$ratio_new;
$copy_height = $height_orig;
} else {
$copy_width = $width_orig;
$copy_height = $width_orig/$ratio_new;
}
//point to start copying from (to copy centre of image if we are cropping)
$dims["src_x"] = ($width_orig - $copy_width)/2;
$dims["src_y"] = ($height_orig - $copy_height)/2;
$dims["copy_width"] = $copy_width;
$dims["copy_height"] = $copy_height;
return $dims;
}

How do i resize image file to optional sizes

I have image upload form, user attaches aimage file, and selects image size to resize the uploaded image file(200kb, 500kb, 1mb, 5mb, Original). Then my script needs to resize image file size based on user's optional size, but im not sure how to implement this feature,
For example, user uploads image with one 1mb size, and if user selects 200KB to resize, then my script should save it with 200kb size.
Does anyone know or have an experience on similar task ?
Thanks for you reply in advance.
With the GD library, use imagecopyresampled().
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
Edit: If you want to resize the image file to a specified size, that's a little harder. All the major image formats use compression and compression rates vary by the nature of what's being compressed. Compress clear blue sky and you'll get a better compression ratio than you will sea of people.
The best you can do is try a particular size is try a particular size and see what the file size is, adjusting if necessary.
Resize ratio = desired file size / actual file size
Resize multipler = square root (resize ratio)
New height = resize multiplier * actual height
New width = resize multiplier * actual width
This basically factors in an approximation of the expected compression ratio. I would expect that you would have some tolerance (like +/- 5%) and you can tweak the numbers as necessary.
There is no direct way to resize to a particular file size. Lastly I'll add that resizing to a particular file size is rather unusual. Resizing to a particular height and/or width (maintaining aspect ratio) is far more common and expected (by users).
Update: as correctly pointed out, this gets the file size wrong. The ratio needs to be the square root of the file size ratios as you're applying it twice (once to height, once to width).
Using the GD Library provided in PHP:
// $img is the image resource created by opening the original file
// $w and $h is the final width and height respectively.
$width = imagesx($img);$height = imagesy($img);
$ratio = $width/$height;
if($ratio > 1){
// width is greater than height
$nh = $h;
$nw = floor($width * ($nh/$height));
}else{
$nw = $w;
$nh = floor($height * ($nw/$width));
}
//centralize image
$nx = floor(($nw- $w) / 2.0);
$ny = floor(($nh-$h) / 2.0);
$tmp2 = imagecreatetruecolor($nw,$nh);
imagecopyresized($tmp2, $img,0,0,0,0,$nw,$nh,$width,$height);
$tmp = imagecreatetruecolor($w,$h);
imagecopyresized($tmp, $tmp2,0,0,$nx,$ny,$w,$h,$w,$h);
imagedestroy($tmp2);imagedestroy($img);
imagejpeg($tmp, $final_file);
This piece of code will take the original image, resize to the specified dimensions. It will first try to ratio aspect resize the image, then crop off + centralize the image, making it fall nicely into the dimensions specified.

Categories