Use PHP to convert PNG to JPEG - php

I have a website where users have been uploading a bunch of high quality PNG files. I want to use PHP to convert them to JPEG and re-size them to make them smaller in file size.
How can I do this when they upload the file? What is the process for doing this? Is a new image created or is it edited?
Thanks

You can use something like this :
function pngTojpg($pngImage, $outputPngFile, $outputJpgFile, $quality) {
$image = imagecreatefrompng($pngImage);
//Save the png image
imagepng($image, $outputPngFile);
//Save the jpeg image
imagejpeg($image, $outputJpgFile, $quality);
// Free up memory
imagedestroy($image);
}
"quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75)"
The php doc : imagejpeg, imagecreatefrompng
These functions are from the GD library, here the installation instruction : Php GD

Use ImageMagick to do all kinds of conversions. You should be able to find examples at this link:
http://www.php.net/manual/en/book.imagick.php

Just try ImageMagick:
http://www.imagemagick.org/script/convert.php
I think, that is what you are looking for.

Well, you can use simple php code to do that but I use and recomend this library to work with images:
Verot - Class Upload http://www.verot.net/php_class_upload.htm
You can convert images to other format, reduce size, transform and do a lot others stuffs.

Related

Force imagejpeg to .png

I have a doubt. Is there a problem if I force imagejpeg to save a .png file?
Like in this example:
imagejpeg($img,$_SERVER['DOCUMENT_ROOT']."/test.png",80);
I want to use this method because I can use the $quality filter.
In this method I have a saved .png file for about 25kb, but if I use imagepng my image is for about 200kb (I used the $quality level from 0-9 but I didn't saw any changes, only -20 kb).
I don't want to make a mistake because my website is generating .png images every second.
Method 2.
I tried to compress the .png images with pngquant but I have no idea how to do it when I am using imagepng function.
I tried something like this, but It doesn't work if I pass the image to the function.
ob_start();
imagepng($img);
$png = ob_get_clean();
file_put_contents($_SERVER['DOCUMENT_ROOT']."/test.png", compress($png);
function compresss($img)
{
//...
}
In other cases if I have $png = $_FILES['file']['tmp_name'] is working. So is there a way to compress with pngquant, or is there a problem if I force imagejpeg to save a .png file?
Your forcing just the filename of the created file. The resulting file will be jpg with all its properties. You will not get a compressed png file if you use the imagejpeg() method.
You need to understand the difference of the both formats. While jpg is a compressed format which loses image information when compressing, png is a lossless format. png also has a compression level, but since no image informatio is destroyed, it will be bigger as an jpg file.
If you use imagepng($image, $filename, 9) you get a png file with the best compression.
You should use imagepng() instead of imagejpeg() to create a png file.
http://php.net/manual/fr/function.imagepng.php

Convert an image from progressive to interlaced without losing quality or details?

I'm trying to retrieve large images from a directory outside of the root directory. At the moment I just use "fpassthru", but this loads the image either progressively or interlaced depending on what is was when uploaded.
How do I create a complete copy of an image but convert it to interlaced without losing any quality or detail with PHP?
If you use the GD libraries that come with PHP, you can use imageinterlace to accomplish this.
Here's from the example:
<?php
// Create an image instance
$im = imagecreatefromgif('php.gif');
// Enable interlancing
imageinterlace($im, true);
// Save the interlaced image
imagegif($im, './php_interlaced.gif');
imagedestroy($im);
?>
Alternately, you could use ImageMagick.

PHP Imagick - convert image to greyscale (very bad result)

I was doing some image editing with PHP, since GD provides less functionalities, I switched to Imagick.
One of the processes is to greyscale images. Everything went fine (locally on Windows 7, Imagick 2.2.1-dev 6.5.8-7 Q16) till I uploaded the script to my web hosting server (Linux, Imagick 3.0.1, 6.2.8, 2010-10-20, Q16).
I'v tried to change the quality, but it didn't improve anything.
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(100);
Here is the results from GD, Imagick and Photoshop
I believe something's wrong with version 3.0.1. Can someone please confirm that?
Q1: Is there an alternative way to convert an image to greyscale with Imagick?
Q2: Is it possible to convert a GD resource to Imagick? So I can use imagefilter($img, IMG_FILTER_GRAYSCALE); to get the correct result and then output with Imagick.
ps: For Q2, you might suggest me to just use GD to process the image. But the problem is that imagejpeg() cannot save images with resolution preserved. and that is actually the reason I switched to Imagick.
This is my preferred way to make a B&W photo in php/imagick: $im = $im->fxImage('intensity');
That applies a function to the image, where intensity is equal to 0.299*red+0.587*green+0.114*blue.
That formula is based on how our eyes are more sensitive to different colours, and as such the difference between that and a "flat" grayscale image really is night and day.
More details here:
http://php.net/manual/en/imagick.fximage.php
http://www.imagemagick.org/script/fx.php
function ImagickToGD($imagick){
$tmpfile = tmpfile();
$imagick->writeImage($tmpfile);
return imagecreatefromstring(file_get_contents($tmpfile));
}
Note that this function does not do any cleanup (except the temp file, which PHP cleans automatically).
So, for example, your code should look like:
$img = new Imagick();
// ...
$gd = ImagickToGD($img);
unset($img); // destroy imagick
imagefilter($gd, IMG_FILTER_GRAYSCALE);
imagejpeg($gd, $target_name, 100);
imagedestroy($gd);
Also, I did not understand the part about "preserving resolution". There is nothing in these operations relating to resolution. My guess is you meant compression? If you want full quality (ie, no compression) simply use 100 as compression value (as I did).
This results in maintaining the existing quality, since opening an image of 70% quality and saving it back with 70% quality actually decreases the final quality by 49% (70% of 70%).
function GDToImagickTo($gd){
$tmpfile = tmpfile();
imagepng($tmpfile); // Png is our best image deal:
// lossless compression, transparency etc..
$imagick = new Imagick()
$imagick->readImage($tmpfile);
return $imagick;
}
Refer this website and check out the image Magick operators found here www.rubblewebs.co.uk/imagemagick/
Also go with www.fmwconcepts.com/imagemagick/ you will find some examples out here...
You can use the image class what you prefer and then use the method readImageBlob to send it to the imagick http://www.php.net/manual/en/imagick.readimageblob.php

imagemagick - downsize/crop/save to jpeg in one go?

I have a php script that will receive a bunch of images uploaded.
What I need to do is create a small thumbnail of each, on the fly using imagemagick.
I can do that easy enough but I also need to crop it so that the thumbnail is always 100x100.
the images supplied won't be the same proportions so simply downsizing won't work.
Can I downsize, crop to 100x100 and save to jpeg all in one step?
I believe this should do what you want:
convert 'just_uploaded/*' -resize 100x100^ -gravity center -extent 100x100 -set filename:f '%t' +adjoin 'just_uploaded_thumbs/%[filename:f].jpg'
resize will downsize, extent (in combination with gravity) will crop, and the rest takes care of saving with a modified name, in JPEG format, in a different directory.
Short answer: no. That'll be 3 steps, no less.
Longer answer: you can do it using the command line interface. In PHP, the only way is to write a function that will do what you ask. Then, for each image, you can just call your function. I'm not sure how this is more beneficial than just using the 3 Imagick functions separately...
I like the sfThumbnailPlugin. It wraps around both ImageMagick or GD
http://www.symfony-project.org/plugins/sfThumbnailPlugin
Example:
public function executeUpload()
{
// Retrieve the name of the uploaded file
$fileName = $this->getRequest()->getFileName('file');
// Create the thumbnail
$thumbnail = new sfThumbnail(150, 150);
$thumbnail->loadFile($this->getRequest()->getFilePath('file'));
$thumbnail->save(sfConfig::get('sf_upload_dir').'/thumbnail/'.$fileName, 'image/png');
// Move the uploaded file to the 'uploads' directory
$this->getRequest()->moveFile('file', sfConfig::get('sf_upload_dir').'/'.$fileName);
// Do whatever is next
$this->redirect('media/show?filename='.$fileName);
}

PHP Image Convert

In my web app users are allowed to upload images as their photos. How can I convert different image extensions to JPG? Input files are JPG, PNG or GIF.
Personally, I prefer Image Magick over GD. It's a lot better if you're dealing with large images too; you can run into memory allocation issues with GD.
With php, you can convert any image to an other using imagepng, imagejpeg, imagegif :
imagepng(imagecreatefromstring(file_get_contents($input)), 'output.png');
In this example, it will save the uploaded image in png with the path 'output.png'
You can use PHP GD.
For anybody who would want to get the binary out of a temporary file, here is my solution:
<?php
$temp = tmpfile();
imagepng(imagecreatefromstring($imgBinary), $temp);
$pathFile = stream_get_meta_data($temp)['uri']; // eg: /tmp/phpFx0513a
$pngBin = file_get_contents($pathFile)
?>

Categories