Converting PNG to JPEG file - php

I have a script to convert PNG files to JPEG files. Except, I'm not exactly sure how it works. What do use for $outputPngFile and $outputJpgFile? Can I do this with a tmp file, like when the user is uploading it? Then, how do I access the new file to move it to the proper image directory?
function pngTojpg($image, $outputPngFile, $outputJpgFile, $quality) {
$image = imagecreatefrompng($image);
//Save the png image
imagepng($image, $outputPngFile);
//Save the jpeg image
imagejpeg($image, $outputJpgFile, $quality);
// Free up memory
imagedestroy($image);
}

<?php
$image = imagecreatefrompng('yourlocation/image.png');
imagejpeg($image, 'yournewlocation/image.jpg', 70);
imagedestroy($image);
?>

It would probably help you to know that you're using the GD library that has been bundled with PHP.
What the function is doing is taking a path to a png image ($image), loading it into a GD resource that can be manipulated within PHP (imagecreatefrompng), saving the image as a png to the png output path ($outputPngFile), then saving the image as a jpg to the jpg output path ($outputJpgFile) with a particular compression factor ($quality), and finally destroying the image resource object, since it isn't needed anymore.
Since it's saving the image as a png as well, the function was obviously intended to be used to save an image from either an external source (given by a URL) or temporary files from a user upload. You can do either, PHP doesn't care so long as the path you provide to the image file is valid.

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

php iphone/IOS6 upload rotation issue: what is best way to save rotated image

Using the safari mobile browser with IOS6, the file upload function gives users the option to snap a photo. Unfortunately, upon snapping the photo, while the photo thumb shows up properly in the browser, when you upload to a server, the file is rotated 90 degrees. This appears to be due to the exif data that the iphone sets. I have code that fixes the orientation by rotating the image when serving. However, I suspect it would be better to save the rotated, properly oriented, image so I no longer have to worry about orientation. Many of my other photos do not even have exif data and i don't want to mess with it if I can avoid it.
Can anyone suggest code to save the image so it is properly oriented?
Here is the code that rotates the image. The following code will display the properly oriented image, however, what I want to do is save it so I can then serve it whenever I want without worrying about orientation.
Also I would like to replace impagejpeg call in code below so that any code works for gifs as well as jpgs.
Thanks for suggestions/code!
PHP
//Here is sample image after uploaded to server and moved to a directory
$target = "pics/779_pic.jpg";
$source = imagecreatefromstring(file_get_contents($target));
$exif = exif_read_data($target);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($source,90,0);
//echo 'It is 8';
break;
case 3:
$image = imagerotate($source,180,0);
//echo 'It is 3';
break;
case 6:
$image = imagerotate($source,-90,0);
//echo 'It is 6';
break;
}
}
// $image now contains a resource with the image oriented correctly
//This is where I want to save resource properly oriented instead of display.
header('Content-type: image/jpg');
imagejpeg($image);
?>
Only JPEG or TIFF files can carry EXIF metadata, so there's no need to worry about handling GIFs (or PNGs, for that matter) with your code.
From page 9 of what I believe is the official specification:
Compressed files are recorded as JPEG (ISO/IEC 10918-1) with application marker segments (APP1 and APP2) inserted. Uncompressed files are recorded in TIFF Rev. 6.0 format.
http://www.cipa.jp/english/hyoujunka/kikaku/pdf/DC-008-2010_E.pdf
To save your image just use the same function imagejpeg and the next parameter to save the image, something like:
imagejpeg($image, $target, 100);
In this case you don't need the specify the header, because you are not showing nothing.
Reference:
http://sg3.php.net/manual/en/function.imagejpeg.php

Use PHP to convert PNG to JPEG

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.

Optimize PNG when resizing with GD/PHP - How to determine color palette?

I had troubles resizing a PNG and maintaining small file sizes. Solution found here.
When resizing the PNG, however, I ran into problems regarding image quality. As far as I could see, GD uses indexed 8-bit-color palette which distorts text and colors get lost, see:
Original Image
Resized Image with solution given above
Resized Image with a tweak²
²The idea for the tweak I found here in stackoverflow: Create truecolor-image, resize it, and copy it to a new image, so the palette is determined based on the resampled result and the image quality is better as you can see in the image above.
// create new image
$newImageTmp = imagecreatetruecolor($newwidth,$newheight);
// we create a temporary truecolor image
// do the image resizing by copying from the original into $newImageTmp image
imagecopyresampled($newImageTmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// create output image
$newImage = imagecreate($newwidth,$newheight);
// copy resized truecolor image onto index-color image
imagecopy($newImage,$newImageTmp,0,0,0,0,$newwidth,$newheight);
// write image to buffer and save in variable
ob_start(); // stdout --> buffer
imagepng($newImage,NULL,6);
$newImageToSave = ob_get_contents(); // store stdout in $newImageToSave
ob_end_clean(); // clear buffer
// remove images from php buffer
imagedestroy($src);
imagedestroy($newImageTmp);
imagedestroy($newImage);
Problem: None of both results are satisfactory.
I am quite sure that there must be a way to 1. determine the color palette, and 2. maintain most of the image's colors, so that 3. the PNG looks similar to the original and has an acceptable file size.
Now, I only see going for JPG instead of PNG. But if you know a solution, it would greatly be appreciated if you let me/us know.
Thank you!
All you need is to replace
$newImage = imagecreate($newwidth,$newheight);
With
$newImage = imagecreatetruecolor($newwidth, $newheight);
Output $maxImgWidth = 200;
PHP's fork of GD doesn't have usable palette generation, so you only get PNG32 with vanialla libpng compression.
For small PNG8 with palette use pngquant, e.g. http://pngquant.org/php.html
And then compress it further with advpng or zopfli-png.

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