I am working to resize and resample some jpeg images using PHP. It take any image greater than 500px by 500px and make the largest side 500px. This should be relatively simple but every time I run the script it makes a black jpeg. The jpeg created has the proper dimensions but does not include the resized image. The GD library is enabled, and I have made sure it is finding the original image. I've been looking at this block of code for a day and half with no luck, what am I not seeing?
<?php
$testimage = 'SandyCayCaribbeanbeach.jpg';
$testfolder = "testimage/testimage.jpg";
list($orgwidth, $orgheight, $type, $attr) = getimagesize($testimage);
echo "org. width " . $orgwidth . "px" . "<br />";
echo "org. height " . $orgheight . "px" . "<br />";
if($orgwidth > 500 || $orgheight > 500){
if($orgwidth > $orgheight){
header('Content-type: image/jpeg');
$ratio = $orgwidth/500;
$newwidth = floor($orgwidth/$ratio);
$newheight = floor($orgheight/$ratio);
$image_p = imagecreatetruecolor($newwidth, $newheight);
$image = imagecreatefromjpeg($testimage);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($image_p, $testfolder, 100);
}
else{
header('Content-type: image/jpeg');
$ratio = $orgheight/500;
$newheight = floor($orgheight/$ratio);
$newwidth = floor($orgwidth/$ratio);
$image_p = imagecreatetruecolor($newwidth, $newheight);
$image = imagecreatefromjpeg($testimage);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($image_p, $testfolder, 100);
}
}
?>
Firstly make sure you have error reporting turned on. Also make sure it can find the source image "SandyCayBaribbeanbeach.jpg".
A simple if(file_exists()) check before handling the image resizing will help trap errors.
I found that I had to specify a full path to the image, not a URL i.e.
/path/to/image.jpg
instead of
http://www.blah.com/image.jpg
to get this to work properly. Hope it helps someone.
Double-check to make sure your source image is truly a JPEG. If you are running Windows, open it up in MS Paint and re-save as a JPEG. This will help rule out the possibility of it being a different format.
I also fought this for a while in a piece of my code recently, and found that imagecopyresampled will even return 1 if the dimensions are not defined. Make sure that your source height and width are set.
Related
I am trying to crop off 45px from the top and bottom of YouTube jpeg thumbnail images, for example this one which is 480px x 360px.
It looks like this:
Notice the 45px black bars on the top and bottom of the image. I simply want those removed such that my resulting image is 480px x 270px and the black bars are gone.
I have achieved partial success by implementing the example from this stack post. Here is my PHP function based on that:
function CropImage($sourceImagePath, $width, $height){
$src = imagecreatefromjpeg($sourceImagePath);
$dest = imagecreatetruecolor($width, $height);
imagecopy($dest, $src, 0, 0, 20, 13, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($dest);
imagedestroy($dest);
imagedestroy($src);
}
And called thusly:
CropImage("LOTR.jpg", 480, 270);
Some cropping occurs, but 2 problems result:
It doesn't crop the top and bottom, rather it seems to crop the left side and the bottom, resulting in this:
From the PHP code snippet I'm using I can't see how to generate a new file. Rather, the PHP script I execute in the browser simply renders the morphed file in the browser. I don't want this to happen, I want to be able to pass a dest path into the function and have it create the new file (and not send anything to the client/browser) with the top 45px and bottom 45px removed. It's obvious that header('Content-Type: image/jpeg'); is part of the problem, but removing that still doesn't give me a destination file written to the server, methinks.
I'm also looking in the PHP docs here. It seems like changing the params in imagecopy($dest, $src, 0, 0, 20, 13, $width, $height); would solve this, but it's really unclear to me what those params should be. The resulting thumbnails inside the YouTube tab look odd with the black bars. Thanks in advance for any advice.
<?php
function CropImage($sourceImagePath, $width, $height){
// Figure out the size of the source image
$imageSize = getimagesize($sourceImagePath);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
// If the source image is already smaller than the crop request, return (do nothing)
if ($imageWidth < $width || $imageHeight < $height) return;
// Get the adjustment by dividing the difference by two
$adjustedWidth = ($imageWidth - $width) / 2;
$adjustedHeight = ($imageHeight - $height) / 2;
$src = imagecreatefromjpeg($sourceImagePath);
// Create the new image
$dest = imagecreatetruecolor($width,$height);
// Copy, using the adjustment to crop the source image
imagecopy($dest, $src, 0, 0, $adjustedWidth, $adjustedHeight, $width, $height);
imagejpeg($dest,'somefile.jpg');
imagedestroy($dest);
imagedestroy($src);
}
I fear that Imagick may not support sharp image resizing. Even the best filters are returning blurry results which are sub par, even horrible in my humble opinion.
This is the BEST quality I can get out of Imagick:
This is resized using TimThumbs:
NOTICE the drastic quality difference? Can anyone provide an example of a sharp image being produced by Imagick?
Below is the Imagick code used to generate the first image:
function imgSize($imagePath,$imageName,$imageExt,$width,$height,$copy) {
$file = "img/".$imageName."-".$width."x".$height.".".$imageExt;
if (!file_exists($file)) {
try {
$image = $imagePath;
$im = new Imagick();
$im->pingImage($image);
$im->readImage($image);
$im->setImageFormat($imageExt);
//$im->thumbnailImage($width,$height,true);
$im->cropThumbnailImage($width,$height);
$im->resizeImage($width,$height,Imagick::FILTER_LANCZOS,0,false);
$im->cropThumbnailImage($width,$height);
if ($imageExt=("jpg"||"JPG")) {
$img->setComression(Imagick::COMPRESSION_JPEG);
$img->setComressionQuality(100);
}
if (!$copy==null) {
$draw = new ImagickDraw();
$draw->setFont("fpdf/font/Montserrat-Regular.ttf");
$draw->setFontSize(35);
$draw->setFillColor("Gray");
$draw->setFillAlpha(0.5);
$draw->setGravity(Imagick::INTERPOLATE_AVERAGE);
$im->annotateImage($draw,0,0,-45,$copy);
}
$im->writeImage("img/".$imageName."-".$width."x".$height.".".$imageExt);
$im->destroy();
return "img/".$imageName."-".$width."x".$height.".".$imageExt;
}
catch(Exception $e) { echo $e->getMessage(); }
}
};
I am aware there are similar questions but there has not been a sufficient answer to this image quality problem. Most attempts to address Imagick's image quality issues are to reduced the problem to, "well that's what you get when you shrink an image." But the TimThumbs image example I have provided in this post disproves that assumption. You can shrink an image and get stunning results using PHP.
This seems better to me, I just resized it 20% of original image. Using GD and 100% quality as JPEG
function resizeImg($filename, $percent, $saveTo) {
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, $saveTo, 100);
imagedestroy($thumb);
}
resizeImg('image.jpg', 0.2, 'image02.jpg');
I have compiled php55-imagick extension to check your code , first of all you have misspelled 2 method names , when fixed resulting image is actually OK setCompression not setComression
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
Here is image with correct methods as showdev commented , doubling image size (121K vs 329K ) , but to me not much benefit
$im->setImageCompression(Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(100);
I am sure this topic has been discussed number of times and I have started doing this from yesterday evening but till now no complete satisfaction.I am using the following code and it gives me a resized image but the scaling is not correct.The height and width is not in it's correct proportion.
I couldn't find any good fiddle like jsfiddle where you can see the output so pasting my code here.
You can see the original image url here also I have attached a resized image.
http://distilleryimage4.s3.amazonaws.com/b1da08e4484511e38e4d0a7011810191_7.jpg
$filename = 'http://distilleryimage4.s3.amazonaws.com/b1da08e4484511e38e4d0a7011810191_7.jpg';
//the resize will be a percent of the original size
$percent = 0.589;
$percent_height = 0.294;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent_height;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb);
imagedestroy($thumb);
This is basically a Math problem:
You are scaling width and height to both different proportions ($percent and $percent_height). You should scale both of them (width and height) by the same percent, to get an image resized to the same ratio. Maybe I didn't understand your question but I think you should change this line:
$newheight = $height * $percent_height;
to
$newheight = $height * $percent;
(and remove $percent_height = 0.294; if we are not gonna use it here)
I would use Imagick. I was doing resizing with imagecreatetruecolor, but it takes a lot of time (0,5 seconds) to resize 1920*1080 image to 150*120.
If you still want to use imagecreatetruecolor: to get the correct scalling use this code.
Is there any script that resizes an external image and outputs it ?
For example, i want to resize all external square images to 130X130.
Like this
http://mydomain.com/script/resize.php?url=http://otherdomain.com/image.png
EDIT:
Facebook also is an example maybe
https://s-external.ak.fbcdn.net/safe_image.php?d=AQCYX3NIE5gMyujT&url=http%3A%2F%2Fi2.ytimg.com%2Fvi%2FyoLeJNjIVZk%2Fhqdefault.jpg
any help appreciated.
Thanks
// Content type
header('Content-Type: image/jpeg');
//get image from internet and save it into local disk
$url = 'http://www.google.com/images/srpr/logo3w.png';
$img = 'google.png';
file_put_contents($img, file_get_contents($url));
//get current size and set new size
list($width, $height) = getimagesize($img);
$new_width = 130;
$new_height = 130;
// genarate resized image copy
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefrompng($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// flush image to browser
imagejpeg($image_p, null, 100);
// save resised image to disk
imagejpeg($image_p, "newimage.jpg",100);
Use this code only if you want to resize and save on your application otherwise above example is enough.
Take a look at this thread. You can write your own code to resize images or use TimThumb script.
if you dont want to save them than you can just set the with and hight with html or css
<img height="130px" with="130px;" src="somesite.com/img.jpg"></img>
I am working on improving my Facebook app. I need to be able to resize an image, then save it to a directory on the server. This is the code I have to resize:
<?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);
?>
My question is, how would I save this resized image? Would I need to? Is there a way to manipulate the resized image without saving it?
According to the manual on imagejpeg(), the optional second parameter can specify a file name, which it will be written into.
Filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
To skip this argument in order to provide the quality parameter, use NULL.
It's usually a good idea to write the results to disk for some basic caching, so that not every incoming request leads to a (resource intensive) GD call.
function resize($img){
/*
only if you script on another folder get the file name
$r =explode("/",$img);
$name=end($r);
*/
//new folder
$vdir_upload = "where u want to move";
list($width_orig, $height_orig) = getimagesize($img);
//ne size
$dst_width = 110;
$dst_height = ($dst_width/$width_orig)*$height_orig;
$im = imagecreatetruecolor($dst_width,$dst_height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($im, $image, 0, 0, 0, 0, $dst_width, $dst_height, $width_orig, $height_orig);
//modive the name as u need
imagejpeg($im,$vdir_upload . "small_" . $name);
//save memory
imagedestroy($im);
}
it should be work
http://www.php.net/manual/en/function.imagecopyresampled.php#90038