image - Is there a shorthand for all the filetypes in imagecreatefromjpeg()/png/gif/etc in PHP?

913

When working with PHP's imagecreatefromXXX()-methods I'm always writing annoying long constructs like this (line breaks are optimized for better readability here), where basically every line and every function used do exactly the same. Looks like a scenario that could be optimized:

switch ($mimeType) {
    case 'image/jpeg': $myImage = imagecreatefromjpeg($source_image); break;
    case 'image/png': $myImage = imagecreatefrompng($source_image); break;
    case 'image/gif': $myImage = imagecreatefromgif($source_image); break;
    // ... and so on, for every possible filetype
    }

Question:

Is there a native function / shorthand in PHP that takes over this annoying long check-for-every-filetype switch ? Seems like this is a common situation but there's no easier way to do this ...

768

Answer

Solution:

Almost. Not from mime type, but from the stream itself:

imagecreatefromstring(file_get_contents($source_image))

imagecreatefromstring() returns an image identifier representing the image obtained from the givenimage. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

(manual)

People are also looking for solutions to the problem: php foreach table display on multidimensional Arrays

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.