PHP - Resize image in server before browser downloads it

北战南征 提交于 2020-01-01 10:57:47

问题


There is a file in stored in the server, which for instance has dimension of 400 X 600 pixels. But in different part of the websites, we need the same picture of different dimension. For thumbnail, we usually need 50 X 50 pixels and if we choose to download the same picture with original dimension, it would take longer and the page load would slow down. If that picture is resized its size would go much more down (like, 500 KB to 50 KB). So, what I want is, before the browser downloads the picture, server should resize the picture to the dimensions as required in PHP script.


回答1:


You need to put the code in thumbnail code in a new file lets say image.php and then use this script as the src of the img tag with parameters of image file name, width and height.

<img src="http://path-to-directory/image.php?img=abc.jpg&width=50&height=50" />

You need change the "DSC01088.jpg" to echo $_GET['img']; after proper validation.




回答2:


You'll need PHP's GD library, then take a look at this and this and then link a php file which resizes instead of the image itself.

Also note the suggestion of neeraj, so you may resize it while uploading to get better performance.

In case if your host lacks PHP GD - which is highly unlikely - you should take a look at this or this.




回答3:


Yes, with the PHP GD2 extension. Here's a quick tutorial




回答4:


Use GD Library to create thumbnails

firstly get list of all the images in folder

 function thumb()
 {
     $img_dir_path='images/';
     $thumb_dir_path='images/thumbs/';

     $img_array=GLOB($img_dit_path.'*.{jpg,jpeg}',GLOB_BRACE);

     foreach($img_array as $img)
     {
       list($path,$file)=explode('/', $img);
       list($fileName, $extension)=explode('.',$file);

        $thumb-file=$thumb_di_path . $fileName. '-thumb.jpg';

         if(file_exists($thumb-file))
         {
               //do nothing 
         }
         else 
         {
            //create file using GD and set width and height proportionally
            // Example $width=$orig_width * 0.1; $height =$orig_height * 0.1  
         }
     } 
 }



回答5:


Yes, of course!

Google for PHP image resize code samples

Then create a download script and call it with the parameters, like this:

http:///www.mysite.com/image.php?image=path/to/my/image.png&width=50&height=50&crop=1

The script will load the image, resize it to the provided width and height and optionally crop it, then echo with appropriate headers for download...

There are a lot of ways of doing this... Sometimes it is just better to use google prior to asking here at SE...



来源:https://stackoverflow.com/questions/11081623/php-resize-image-in-server-before-browser-downloads-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!