PHP resize image to fit within a certain area - php

I have an image file that is stored within the variable $image I want to resize this image so it would fit within an area of 380px by 380px (so which means that the tallest side of the image must be 380px on the other side smaller than 380px).
Has anyone a suggestion on how to do this?
Thanks

here is what I use to keep it under 800x600
$orig_image = imagecreatefromjpeg($file['tmp_name']);
list($width,$height) = getimagesize($file['tmp_name']);
if(max($width,$height) > 800){
$scale = 800/max($width,$height);
$new_width = floor($width*$scale);
$new_height = floor($height*$scale);
$save_image = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($save_image,$orig_image,0,0,0,0,$new_width,$new_height,$width,$height);
imagejpeg($save_image,self::$FILE_DIRECTORY."$year_month/$fileId.jpg");
$orig_image = $save_image;
$width = $new_width;
$height = $new_height;
}
hopefully you can extrapolate a solution off that.. also not that my $file variable is coming from an uploaded file in the $_FILE array.

Related

How to resize image keeping constraints php

I have made two GIFs to explain what I am trying to do. Where the grey border is the dimensions I am after (700*525). They are at the bottom of this question.
I want for all images that are larger than the given width and height to scale down to the border (from the centre) and then crop off the edges. Here is some code I have put together to attempt this:
if ($heightofimage => 700 && $widthofimage => 525){
if ($heightofimage > $widthofimage){
$widthofimage = 525;
$heightofimage = //scaled height.
//crop height to 700.
}
if ($heightofimage < $widthofimage){
$widthofimage = //scaled width.
$heightofimage = 700;
//crop width to 525.
}
}else{
echo "image too small";
}
Here are some GIFs that visually explain what I am trying to achieve:
GIF 1: Here the image proportions are too much in the x direction
GIF 2: Here the image proportions are too much in the y direction
image quality comparison for #timclutton
so I have used your method with PHP (click here to do your own test with the php) and then compared it to the original photo as you can see there is a big difference!:
Your PHP method:
(source: tragicclothing.co.uk)
The actual file:
(source: mujjo.com)
The below code should do what you want. I've not tested it extensively but it seems to work on the few test images I made. There's a niggling doubt at the back of mind that somewhere my math is wrong, but it's late and I can't see anything obvious.
Edit: It niggled enough I went through again and found the bug, which was that the crop wasn't in the middle of the image. Code replaced with working version.
In short: treat this as a starting point, not production-ready code!
<?php
// set image size constraints.
$target_w = 525;
$target_h = 700;
// get image.
$in = imagecreatefrompng('<path to your>.png');
// get image dimensions.
$w = imagesx($in);
$h = imagesy($in);
if ($w >= $target_w && $h >= $target_h) {
// get scales.
$x_scale = ($w / $target_w);
$y_scale = ($h / $target_h);
// create new image.
$out = imagecreatetruecolor($target_w, $target_h);
$new_w = $target_w;
$new_h = $target_h;
$src_x = 0;
$src_y = 0;
// compare scales to ensure we crop whichever is smaller: top/bottom or
// left/right.
if ($x_scale > $y_scale) {
$new_w = $w / $y_scale;
// see description of $src_y, below.
$src_x = (($new_w - $target_w) / 2) * $y_scale;
} else {
$new_h = $h / $x_scale;
// a bit tricky. crop is done by specifying coordinates to copy from in
// source image. so calculate how much to remove from new image and
// then scale that up to original. result is out by ~1px but good enough.
$src_y = (($new_h - $target_h) / 2) * $x_scale;
}
// given the right inputs, this takes care of crop and resize and gives
// back the new image. note that imagecopyresized() is possibly quicker, but
// imagecopyresampled() gives better quality.
imagecopyresampled($out, $in, 0, 0, $src_x, $src_y, $new_w, $new_h, $w, $h);
// output to browser.
header('Content-Type: image/png');
imagepng($out);
exit;
} else {
echo 'image too small';
}
?>
Using Imagick :
define('PHOTO_WIDTH_THUMB', 700);
define('PHOTO_HEIGHT_THUMB', 525);
$image = new Imagick();
$image->readImage($file_source);
$width = $image->getImageWidth();
$height = $image->getImageHeight();
if($width > $height){
$image->thumbnailImage(0, PHOTO_HEIGHT_THUMB);
}else{
$image->thumbnailImage(PHOTO_WIDTH_THUMB, 0);
}
$thumb_width = $image->getImageWidth();
$thumb_height = $image->getImageHeight();
$x = ($thumb_width - PHOTO_WIDTH_THUMB)/2;
$y = ($thumb_height - PHOTO_HEIGHT_THUMB)/2;
$image->cropImage(PHOTO_THUMB_WIDTH, PHOTO_THUMB_HEIGHT, $x, $y);
$image->writeImage($thumb_destination);
$image->clear();
$image->destroy();
unlink($file_source);
I have used GD library to accomplish the resize. Basically what I did is, I calculated the image dimension and then resized the image to dimension 700x525 from the center.
<?php
/*
* PHP GD
* resize an image using GD library
*/
//the image has 700X525 px ie 4:3 ratio
$src = 'demo_files/bobo.jpg';
// Get new sizes
list($width, $height) = getimagesize($src);
$x = 0;
$y = 0;
if($width < $height){
$newwidth = $width;
$newheight = 3/4 * $width;
$x = 0;
$y = $height/2 - $newheight/2;
}else{
$newheight = $height;
$newwidth = 4/3 * $height;
$x=$width/2 - $newwidth/2;
$y=0;
}
$targ_w = 700; //width of the image to be resized to
$targ_h = 525; ////height of the image to be resized to
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$newwidth,$newheight);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
?>
i used http://phpthumb.sourceforge.net to have a beutiful solution also with transparent curved edges.
this is an alternative route to solution, might suit someone's need with little configuration.

How to get image size from a canvas?

Is it possible to get the image size in pixels from a canvas?
E.g. I know I can achieve it getting the size from the image directly:
list($width, $height) = #getimagesize($_FILES['inputFieldName']['tmp_name'])
but I want to get it from a canvas. E.g.:
$canvas = imagecreatefromjpeg($image_path);
//Get image size from $canvas
Try:
$canvas = imagecreatefromjpeg($image_path);
$width = imagesx($canvas);
$height = imagesy($canvas);
Details at http://es1.php.net/manual/en/function.imagesx.php and http://es1.php.net/manual/en/function.imagesy.php

How to save new image dimensions after scaling during upload?

QUESTION EDITED
Below is a simple script to allow users upload pictures. Once the upload is done, the pictures are displayed as a 170px(h) x 150px(w) thumbnail.
Most of the pictures look distorted once resized, so I guess I need to scale them too.
I'm stuck at saving the new image dimensions. See TODO.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$maxWidth = 150;
$maxHeight = 170;
$name = $_FILES ['image'] ['name'];
$type = $_FILES ["image"] ["type"];
$size = $_FILES ["image"] ["size"];
$tmp_name = $_FILES ['image'] ['tmp_name'];
list($originalWidth, $originalHeight) = getimagesize($tmp_name);
if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
if ($originalWidth / $maxWidth > $originalHeight / $maxHeight)
{
// width is the limiting factor
$width = $maxWidth;
$height = floor($width * $originalHeight / $originalWidth);
} else {
// height is the limiting factor
$height = $maxHeight;
$width = floor($height * $originalWidth / $originalHeight);
}
// Resample
$image_p = imagecreatetruecolor($maxwidth, $maxheight);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxwidth, $maxheight,
$originalWidth, $originalHeight);
TODO: how do I save the new dimensions to $location ?
//start upload process
$RandomNumber = uniqid();
$location = "uploads/$RandomNumber";
move_uploaded_file($tmp_name, $location);
query("UPDATE users SET profilepic = '".$location."' WHERE id = '$id'");
}
?>
Some of my code is inspired from this question:
Distorted image resize with PHP
As for you question: "How can I get the initial dimensions of the picture the user wants to upload?"
From the manual:
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
With that in mind, you may be able to replace the file path in the above example with $_FILES["image"] to get the dimensions data.
Once you have the original dimensions, you can adjust the image to be smaller while preserving the original aspect ratio.
For error checking, you would probably want to either check that there is only one file in $_FILES["image"], or loop through an array in the event you allow for multiple image uploads using the same name for each image's HTML input tag.
I have a custom class that helps me do this in projects. Feel free to use my code:
https://gist.github.com/695Multimedia/7117003

php thumbnail - creates a grainy back and white image

My code below creates the thumb but it is pretty grainy and although not black and white looks pretty washed out.
Any ideas how I can create a better quality thumb?
$thumb = $targetPath."Thumbs/".$fileName;
$image = imagecreatefromjpeg($targetFile);
$width = 200; //New width of image
$height = 92; //This maintains proportions
$thumbWidth = 200;
$thumbHeight = 92;
$sourceImage = imagecreatefromjpeg($targetFile);
$targetImage = imagecreate($thumbWidth,$thumbHeight);
imagecopyresampled($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage));
//imagejpeg($targetImage, "$thumbPath/$thumbName");
imagejpeg($targetImage, $thumb, 100);
chmod($thumb, 0755)
;
thanks R.
use imagick, it will give way better results http://lt.php.net/manual/en/function.imagick-thumbnailimage.php
Use this: ini_set("gd.jpeg_ignore_warning", 1);

PHP GD imagecreatefromjpeg cant handle big size image?

my project is when im uploading an image automatically my program will create the thumb size.My program work normally if the size of picture about 1024x768 But when i'm uploading image with size 1576x2379 showing error like this:
Allowed memory size of 8388608 bytes exhausted (tried to allocate 1576 bytes)
I'm using method imagcreatefromjpeg().How can I create thumb version from big size image using PHP???
thanks
You have to edit your php.ini
Find the line with Memory limit statement and change its default value for something bigger - for example 128M
For me this problem solved with next peace of code:
first of all you need imagemagick on your server;
and install it also as part of php (php5-imagick)
my part of code (for Smart Image Resizer 1.4.1 )
i found line "$src = $creationFunction($docRoot . $image);"
and replace with
if ( $width >= 1900 )
{
// Read original image and create Imagick object
$thumb = new Imagick($docRoot . $image);
$newX = 1600;
$newY = 1200;
// Scale the image
$thumb->thumbnailImage($newX,$newY);
#$thumb->cropThumbnailImage(600,600);
// make new file-name
$_ext_pos = strrpos($image,'.');
$_image_name_p1 = substr($image, 0, $_ext_pos);
$_image_name_p2 = substr($image, $_ext_pos);
$thumbnailFilename = $_image_name_p1.'_s600'.$_image_name_p2;
// Write the new image to a file
$thumb->writeImage($docRoot . $thumbnailFilename);
$thumb->destroy();
// Read in the original image
$src = $creationFunction($docRoot . $thumbnailFilename);
// reset w-h
$size = GetImageSize($docRoot . $thumbnailFilename);
$width = $size[0];
$height = $size[1];
// Setting up the ratios needed for resizing.
// resize the image (based on height or based on width)
$xRatio = 1;#$maxWidth / $width;
$yRatio = 1;#$maxHeight / $height;
if ($xRatio * $height < $maxHeight)
{ // Resize the image based on width
$tnHeight = ceil($xRatio * $height);
$tnWidth = $maxWidth;
}
else // Resize the image based on height
{
$tnWidth = ceil($yRatio * $width);
$tnHeight = $maxHeight;
}
}
else
{
// Read in the original image
$src = $creationFunction($docRoot . $image);
}
so I replace the "ImageCreateFromJpeg" for large images with imagick-workflow
good luck!

Categories