Pergunta

is there a way that i can use createimagefromjpeg() to save an image from a url but allow all image file types?

It seems obvious that createimagefromjpeg only allows jpeg / jpg.

Here is my current process:

    // create the image and save it
    $imagefile = iageURL;
    $resource = imagecreatefromjpeg($imagefile);
    // X amount of quality is the last number
    imagejpeg($resource, "images/covers/imagename.jpeg", 50);
    imagedestroy($resource);

This works great because it allows me to reduce the image quality. But i get an error when trying to use anything other than a jpeg / jpg.

Is there a way around this? Or perhaps a better method of saving images (at a reduced quality) from a url.

Craig.

Foi útil?

Solução

You need to check the file type - the best way is to check the mime type if you can, then you can do a switch and utilize the other image creation functions in GD lib such as imagecreatefromgif() and imagecreatefrompng() etc:

switch($mime_type) {
    case 'image/jpeg':
    case 'image/jpg':
        $img = imagecreatefromjpeg($filename);
        break;
    case 'image/png':
        $img = imagecreatefrompng($filename);
        break;
    case 'image/gif':
        $img = imagecreatefromgif($filename);
        break;
}

Another option is for you to grab the image's data into a string and use imagecreatefromstring() to create an image handle from raw data:

$filename = 'http://yoursite.com/yourlogo.jpg';
$img = imagecreatefromstring(file_get_contents($filename));

From the manual: These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top