views:

59

answers:

2

I need to convert a .JPG, .JPEG, .JPE, .GIF, etc to a .PNG from my PHP webpage without using ImageMagick. Any ideas?


Here is the code I found and am trying to work with:

<?php
header("content-type: image/png");
$original_filename = $_HTTP_POST_FILES['uploaded_file']; 
imagepng($original_filename,'border/testconvert.png',9);

?>
+2  A: 

Who needs ImageMagick? Take a look at the built-in image functions using gd.

EDIT Basic example:

<?php
 $filename = "myfolder/test.jpg";
 $jpg = @imagecreatefromjpeg($filename);
 if ($jpg)
 {
   header("Content-type: image/png");
   imagepng($jpg);
   imagedestroy($jpg);
   exit;
 }

 // JPEG couldn't be loaded, maybe show a default image
?>

You can do more with this such as change compression and quality values etc, save the output to a file instead of outputting to the browser and so on - check the docs for further info :-)

Note that the image functions issue warnings/notices etc if there are problems loading an image, hence the use of the @ symbol to suppress, otherwise you'll get spurious output instead of just the image data.

richsage
gd is not always available either. You need to compile PHP with `--with-gd`.
Matthew Flaschen
I can use GD, I've used it with other image manipulation tasks I had. I just can't figure out how to convert the images.
Zachary Brown
And if you're allowing multiple file types, you'll have to setup a check to see what the extension is and run a switch to load the image based on its file type or just load a default image if it doesn't match anything.
animuson
This will do just fine! Thanks!
Zachary Brown
Re the @ -- it would be much better to turn errors off for the page altogether (`error_reporting(0);`). Suppressing individual errors dramatically slows performance, even when no errors occur.
lonesomeday
OK, your example works perfectly. But, I can't seem to find anything about converting .BMP to .PNG... any ideas?
Zachary Brown
Who needs imagemagick? Anyone that wants a very simple solution to otherwise bulky image handling. Yeah you don't NEED it, but it is a very useful tool for so many reasons. It improved the productivity of our firm substantially with easy to understand, single line conversions.
Kai Qing
@Kai I don't doubt it - it is a useful tool. The OP asked for a solution that didn't use it however :-)
richsage
A: 
function jpg2png($originalFile, $outputFile, $quality) {
    $image = imagecreatefromjpeg($originalFile);
    imagepng($image, $outputFile, $quality);
    imagedestroy($image);
}

Try something like this.

Tell me if if works!!

Good luck

Trufa
It was the same logic (ish) used in the first example, and yes.. it works great! But, would you happen to know about converting .BMP to .PNG?
Zachary Brown
No but you should really start a question on that particular topic because might be really interesting. Good luck!
Trufa