Imagemagick resize images dynamically - php

I have created a App wehere the user can upload an Image and choose a region to crop. Afterward the image should be resized and cropped with the chosen coordinates.
The problem is, that those image are printed afterwards, so the quality should be as close to the original image as possible(without artifacts, or visible blur).
Anyway resizing causes a loss of quality and using unsharpmask() after resizing makes it a lot better, but it still differs from image to image.
Oh and sometimes the colours don't even match with the original :(
I know this function's parameters depend on things like the size and saturation of the image, but is there any way to calculate the best parameters?
Here's what I have so far:
$origPath = "ThePathToTheFileOnTheServer.jpg";
move_uploaded_file( $_FILES['imagefile']['tmp_name'],$origPath);
$img = new Imagick();
$file_handle_for_viewing_image = fopen($origPath, 'a+');
$img->readImageFile($file_handle_for_viewing_image);
fclose($file_handle_for_viewing_image);
$img->setImageFormat('jpg');
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(100);
$img->resizeImage ( 0, $targ_h, Imagick::FILTER_LANCZOS, 1);
$img->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
$img->cropImage($targ_w, $targ_h, $xPos, 0);
$newimg = new Imagick();
$newimg->newImage($targ_w,$targ_h,new ImagickPixel('white'));
$newimg->setImageFormat('jpg');
$newimg->setImageCompression(Imagick::COMPRESSION_JPEG);
$newimg->setImageCompressionQuality(100);
$newimg->compositeImage($img,Imagick::COMPOSITE_OVER,0,0);
$newimg->writeImage("TheNewImage.jpg");
It does what it should, but can I somehow calculate the parameters of $img->unsharpMaskImage(0 , 0.5 , 1 , 0.05); to fix the current Image?
Thanks for your help!
Here's an example:
original:
after resize:

You could try resizing in the Lab colourspace and then converting back to sRGB afterwards. At the command-line, that would be
convert input.jpg -colorspace Lab -resize ... -colorspace sRGB result.jpg

Related

Image file size differences between Imagemagick and GD library

I have been doing some tests and found out that Imagemagick creates larger file sized images compared to GD library.
I have tried using thumbnailImage method and also resizeImage method (with different filters) of Imagemagick for creating an image of max dimension 1024x680 jpeg with JPEG compression and quality 80 and at 72 pixels per inch resolution and am also using stripImage method to remove unneeded meta data. The file size created by Imagemagick is always in the range of 700KB to 800KB depending upon various filters. On the other hand GD library produces an image of size 1024x680 which is only 41KB in size.
Can anyone please explain the difference in file sizes. I opened up the 2 files in Photo shop and checked to see any differences but could not find any (DPI, color profile, 8 bit channel etc), but still cant explain the difference in file sizes.
$srgbPath = "pathTosrgbColorProfile";
$srgb = file_get_contents($srgbPath);
$image->profileImage('icc', $srgb);
$image->stripImage();
$image->setImageResolution(72,72);
$image->setImageUnits(1);
$image->setInterlaceScheme(Imagick::INTERLACE_JPEG);
$image->setImageCompression(imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(80);
$image->setColorspace(imagick::COLORSPACE_SRGB);
$image->resizeImage($thumb_width,$thumb_nheight,imagick::FILTER_CATROM,1);
$image->writeImage($destination);
The size went down by 40KB giving an output of 711KB which is still pretty big. The Hi-res original file I am testing on is a jpeg of size 3008x2000 (4.2MB).
Edit:
I think I figured it out, the method setCompression() does it for the Object and not the image, instead I used setImageCompression() and setImageCompressionQuality() and now the size has reduced to 100KB.. All good now!
Maybe the Quality settings of GD and ImageMagick aren't easily comparable, 80% in one does not mean the same as 80% in the other. I found the following note in an article form Smashing Magazine:
It turns out that JPEG quality scales are not defined in a specification or standard, and they are not uniform across encoders. A quality of 60 in Photoshop might be the same as a quality of 40 in one program, quality B+ in another and quality fantastico in a third. In my tests, I found that Photoshop’s 60 is closest to -quality 82 in ImageMagick.
So you may pay more attention on quality when comparing the different result files. Maybe the colors differ or the gd image has more artifacts.
The differnce seems rather large; when I did some tests a couple of years ago the file size of IM was about 5x the size of GD.
It would be interesting to see your actual code used.
I am at work at the moment but have a photo resized to 592 x 592 and the filesize is 50.3KB I know it is not the same size as yours but it was saved at quality 100
You can run this and see what IM says about the output files:
convert image -verbose -identify
EDIT:
You must be doing something wrong I have just run a test and the results are below - For some reason the thumbnail size is the same as the resize size! Maybe a bug.
Original file size: 4700 x 3178 2.31MB
-resize dimensions = 1021 x 680 186kb
-thumbnail dimensions = 1021 x 680 186kb
GD dimensions = 1024 x 682 100kb
$original = 'IMG_4979_1.CR2';
// Convert to jpg as GD will not work with CR2 files
exec("convert $original image.jpg");
$image = "image.jpg";
exec("convert $image -resize 1024x680 output1.jpg");
exec("convert $image -thumbnail 1024x680 -strip output2.jpg");
// Set the path to the image to resize
$input_image = 'image.jpg';
// Get the size of the original image into an array
$size = getimagesize( $input_image );
// Set the new width of the image
$thumb_width = "1024";
// Calculate the height of the new image to keep the aspect ratio
$thumb_height = ( int )(( $thumb_width/$size[0] )*$size[1] );
// Create a new true color image in the memory
$thumbnail = ImageCreateTrueColor( $thumb_width, $thumb_height );
// Create a new image from file
$src_img = ImageCreateFromJPEG( $input_image );
// Create the resized image
ImageCopyResampled( $thumbnail, $src_img, 0, 0, 0, 0, $thumb_width, $thumb_height, $size[0], $size[1] );
// Save the image as resized.jpg
ImageJPEG( $thumbnail, "output3.jpg" );
// Clear the memory of the tempory image
ImageDestroy( $thumbnail );

image resizing in PHP

While i was doing some image processing, i found out that GD and Imagick in PHP does not resize image to color pixel identical level, which in most cases, were not needed.
Now in case, i need a image from whatever dimension to scale to 256*256
To make sure the TEST results are consistent, i used a 256*256 image and resize it to it's own size.
what i've attempted:
imagecopyresized($new, $img, 0, 0, $x, 0, $width, $height, $w, $h); //256 , 256
and
$compression_type = imagick::COMPRESSION_NO;
$images_ima = new Imagick($image_path); //$image_path = path to image...
$images_ima->setImageCompression($compression_type);
$images_ima->setImageCompressionQuality(100);
$images_ima->sampleImage($X_SIZE,$Y_SIZE); // 256 ,256
$images_ima->writeImages($dest_path, true); //destination path
none of them worked, if i compare the output with the original image, it will look something like this:
it looks like the functions i've used are resampling the image since the variations in the RGB value between both image are small
i can achieve pixel to pixel identical resizing from 256*256 to 256*256 in photoshop, OSX preview, and even Pixelformer.
i was wondering how can that be done i PHP?
Since your image format (jpeg - assumed from 100 quality setting) is a lossy format you won't get a lossless throughput this way as you're recompressing the image.
You should try to detect image dimensions and use the original image if the dimensions are already correct.
When you don't change the dimensions (original dimensions = dimensions after resizing) in Photoshop or OSX preview they won't recompress the image, that's why you won't see any change.

PHP GD :image re size with some black rectangles?

I am trying to accomplish this task for 2 days, read various stuffs online but still can't find out what is happen, also read all here at SO about similar problems but nothing.
I have image 400x400 and want to generate 120x120 using php gd. using this code:
$image_p = imagecreatetruecolor(120,120);
$image = imagecreatefromstring($X_IMAGE);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, 120, 120, 400, 400);
// RETURN
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 70);
//destroy...
$X_IMAGE is 400x400 JPG that is stored as string.
All images are generated in 120x120 but most of them have some BLACK rectangle at bottom at some pictures it is larger on some it is smaller but 50% of images are with that square. So all are VISIBLE, just some part of image is covered with that black color. What would be solution for my problem? All source images are JPG and also those 120x120 that I need are JPG as you can see...
The problem is that your original image is not a square! You pass 400x400 to imagecopyresampled, but the height of the original image maybe is not 400px!
In the image you posted, for example, you have a not-squared original image. When you tell PHP to resample a square on anther image resource, you will resample the image plus a non-existent rectangle at the bottom.
The solution depends on what you want to output.
Do you want a scaled image that keeps ratio? For example, from 400x300 to 120x90.
Or a scaled image that not keeps ratio? For example, from 400x300 to a distorted 120x120?
Or a cropped thumbnail? 400x300 to a 120x120 with left and right parts trimmed out a little?
Do you want to replace the black rectangle with a white one, so fill the resampled image in that way?

Bad quality of GIF image in PHP GD

I have a watermark script I am working on, the results are good on PNG and on JPG images however a gif image, not so good. I am using PHP and GD
Below you can see the difference in quality of the watermark.
Anyone know how to improve this?
For the gif version I am using
$image = imagecreatefromgif($source_file);
imagecopymerge($image, $watermark, $x, $y, 0, 0, $water_width, $water_height, 65);
imagegif($image, $source_file);
gif image = bad quality
gif image http://img2.pict.com/fd/46/00/1471179/0/gif.gif
jpg image = good
jpg image http://img2.pict.com/82/a1/5a/1471181/0/jpg.jpg
GIF images have a fixed palette that can contain a maximum of 256 colors. The issue here is probably that the image your inserting uses colors that isn't available in the target image.
I have never tried this, but it might be worth a shot. You could try converting the gif image to a true color image first, then do the watermarking and after that converting it back to gif.
$image = imagecreatefromgif($source_file);
// create a true color image of the same size
$image2 = imagecreatetruecolor(imagesx($image), imagesy($image));
// copy the original gif image on to the true color image
imagecopy($image2, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
// copy the watermark onto the new true color image
imagecopymerge($image2, $watermark, $x, $y, 0, 0, $water_width, $water_height, 65);
// write the new image to disk
imagegif($image2, $source_file);
Try it and see if it makes a difference.
There's also a couple of palette manipulation functions available that might help:
imagecolormatch()
imagetruecolortopalette()
imagepalettecopy()
I'm not sure how you would apply them, but I'm guessing that there's a few things you could do to improve the results.
GIF only supports a color palette of 256 colors. Therefore, the colors of your watermark image have to be mapped to this palette. This caused them to be rendered and saved with different colors than before. Due to this small palette, GIF is not recommended for photos in general, anyways.
GIF images will never look great, as the colour palette is 256 colours. As MrMage says, colour mapping causes a severe approximation of the true colours of the image. You are better off with PNGs, they do support transparency.

Php Gd rotate image

HEllo,
I am trying to rotate a circular image around the center and then cut off the sides. I see the imagerotate function, but it does not seem to rotate about centre.
Anyone have any suggestions?
Thank you.
Update: Since it is a circle, I want to cut off the edges and keep my circle in the same dimensions.
The documentation says that it does rotate around the center.
Unfortunately it also says that it will scale the image so that it still fits. That means that whatever you do this function will change the size of your internal circular image.
You could (relatively easily) calculate how much scaling down will happen and then prescale the image up appropriately beforehand.
If you have the PHP "ImageMagick" functions available you can use those instead - they apparently don't scale the image.
I faced successfully that problem with the following code
$width_before = imagesx($img1);
$height_before = imagesy($img1);
$img1 = imagerotate($img1, $angle, $mycolor);
//but imagerotate scales, so we clip to the original size
$img2 = #imagecreatetruecolor($width_before, $height_before);
$new_width = imagesx($img1); // whese dimensions are
$new_height = imagesy($img1);// the scaled ones (by imagerotate)
imagecopyresampled(
$img2, $img1,
0, 0,
($new_width-$width_before)/2,
($new_height-$height_before)/2,
$width_before,
$height_before,
$width_before,
$height_before
);
$img1 = $img2;
// now img1 is center rotated and maintains original size
Hope it helps.
Bye
According to the PHP manual imagerotate() page:
The center of rotation is the center
of the image, and the rotated image is
scaled down so that the whole rotated
image fits in the destination image -
the edges are not clipped.
Perhaps the visible center of the image is not the actual center?

Categories