0

Recently I heard of the possibility to get different versions of an uploaded image on the fly via php's header('Content-Type: image/jpeg');.

So instead of:

<img src="files/myimage-thumb.jpg">
<img src="files/myimage-midsized.jpg">
<img src="files/myimage-original.jpg">

you could do:

<img src="script/getimage.php?v=thumb">
<img src="script/getimage.php?v=midsized">
<img src="script/getimage.php?v=original">

then the script runs and via header('Content-Type: image/jpeg'); … it returns an image which was generated on the server (client?) .. temporarily..

IS THIS A GOOD IDEA?

I'm a bit sceptic, because I could imagine that it takes lot more time and performance!?

John Doe Smith
  • 1,623
  • 4
  • 24
  • 39
  • 2
    **NO.** http://stackoverflow.com/a/9468009/285587 – Your Common Sense Mar 03 '13 at 13:28
  • 1
    *dynamically* creating those images for each request is probably a bad idea as it *will* take longer to generate them. The best option is to resize the images and *save* the resized images on the webserver. That way the image only needs to be resized once and they become just 'regular' images – thaJeztah Mar 03 '13 at 13:28
  • 1
    I suppose you could dynamically create the images once, save them, and then use the saved versions on following requests, but unless you have to make some kind of logic test before presenting an image (access control, retrieval from database, etc) then it makes no sense to go through PHP to serve an image. – cernunnos Mar 03 '13 at 13:33
  • @YourCommonSense maybe I misread, the question you're linking to says that "on the fly" resizing *should be used* until you get too many visitors or it causes your server to 'overheat' – thaJeztah Mar 03 '13 at 13:34
  • @cernunnos an option for that is to create a mod_rewrite rule that will only point to the php-script if the requested (scaled) image is not present, otherwise scale and create it – thaJeztah Mar 03 '13 at 13:36

1 Answers1

0

I do that creating a new image and storing on a cache folder then next time if the image already exists i retrieve it or create it.

Something like this:

    function resize_image($filename, $width, $height)
    {
    if (!file_exists($filename) || !is_file($filename))
    {
        return false;
    } 

    $info = pathinfo($filename);
    $extension = $info['extension'];
            $new_image = 'cache/' . utf8_substr($filename, 0, strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;

            if (file_exists($new_image))
                    {
                      return $new_image;
                    }
                return new_iamge($filename, $width, $height);

}