3

I currently have an image upload input that only accepts PNG, JPG/JPEG, GIF images. If the file is valid, it then proceeds to create a thumbnail from the image using

imagecreatefrompng()
imagecopy()
imagejpg()

This works fine, but ONLY for png images, obviously.

What is the most logical and efficient way to use "imagecreatefrompng()" except using the proper file format that was submitted? All I can think of is if/else using multiple "imagecreatefrom__()" but that doesn't seem right.

Also, how can my outputted format always be PNG no matter what was submitted instead of the current imagejpg() I have now.

Aaron
  • 1,956
  • 5
  • 34
  • 56
  • images, once loaded by GD, are all stored internally in the exact same format. It's only upon loading and saving that you have to pick the appropriate file type, and saving to any other file type is also possible. – Marc B Dec 05 '11 at 19:14

2 Answers2

9

You will have to use a switch and determine the image type like so:

    $extension = strtolower(strrchr($file, '.'));

    switch ($extension) {
        case '.jpg':
        case '.jpeg':
            $img = @imagecreatefromjpeg($file);
            break;
        case '.gif':
            $img = @imagecreatefromgif($file);
            break;
        case '.png':
            $img = @imagecreatefrompng($file);
            break;
        default:
            $img = false;
            break;
    }

-EDIT- Didn't see the second part of your question, you just need to save it using imagepng to save it to a PNG, no need to do anything else.

jValdron
  • 3,408
  • 1
  • 28
  • 44
8

Using imagecreatefromstring( file_get_contents( $filename)) would be the lazy option here.

And if you always want a png output, then just exchanging imagejpg for imagepng would do.

mario
  • 144,265
  • 20
  • 237
  • 291