How to Reduce or Compress Image File Size while Uploading Using PHP code?


It is a quite common process to upload images on the websites dynamically. However, while you upload the image with large file size in a website, it is likely to take more time to load. This necessitates the developer to write down the code to decrease the file size of image while dynamically uploading the image to the website. With the help of PHP coding, it is possible to reduce the size of files of uploaded images when they are loading. Definitely, you would have to compromise with the image quality i.e. is the file size has to be reduced. 

Below is the Code to reduce file size for the image:

	function compress($source, $destination, $quality) {

		$info = getimagesize($source);

		if ($info['mime'] == 'image/jpeg') 
			$image = imagecreatefromjpeg($source);

		elseif ($info['mime'] == 'image/gif') 
			$image = imagecreatefromgif($source);

		elseif ($info['mime'] == 'image/png') 
			$image = imagecreatefrompng($source);

		imagejpeg($image, $destination, $quality);

		return $destination;

	$source_img = 'source.jpg';
	$destination_img = 'destination .jpg';

	$d = compress($source_img, $destination_img, 90);
$d = compress($source_img, $destination_img, 90);

PHP function is used in the code that will pass the source image, destination image and quality for the image that takes to compress.

$info = getimagesize($source);

The getimagesize() function is also used to know the size of given image file and to return the dimensions including the file type.

$info = getimagesize($source);


Array ( [0] => 1280 [1] => 768 [2] => 2 [3] => width="1280" height="768" [bits] => 8 [channels] => 3 [mime] => image/jpeg )
$image = imagecreatefromjpeg($source);
$image = imagecreatefromgif($source);
$image = imagecreatefrompng($source);

All the functions used in the coding are intended to make a new image from the given URL or file. Those functions are meant for returning an image identifier indicating the image acquired from the given file name.

imagejpeg($image, $destination, $quality);

The imagejpeg() function is added in the code to make a JPEG file from the provided image.

Syntax: imagejpeg ( $source_image, $destination_image, $quality )

Quality ($quality): Quality is optional that range from 0 representing the worst quality and smaller file to hundred representing the best quality and biggest file. The range75 is considered as the default.
The GD library is utilized for creating dynamic image. GD library is used to create JPG, PNG or GIF. This is more essential to run every image creation function in PHP language. When your server is not compatible with GD library, then the complete functionality associated with the image creation won’t work out.

Here is the Complete code to reduce the image file size using PHP:

$name = ''; $type = ''; $size = ''; $error = '';
   function compress_image($source_url, $destination_url, $quality) {

      $info = getimagesize($source_url);

          if ($info['mime'] == 'image/jpeg')
          $image = imagecreatefromjpeg($source_url);

          elseif ($info['mime'] == 'image/gif')
          $image = imagecreatefromgif($source_url);

          elseif ($info['mime'] == 'image/png')
          $image = imagecreatefrompng($source_url);

          imagejpeg($image, $destination_url, $quality);
          return $destination_url;

            if ($_POST) {

            if ($_FILES["file"]["error"] > 0) {
            $error = $_FILES["file"]["error"];
            else if (($_FILES["file"]["type"] == "image/gif") ||
            ($_FILES["file"]["type"] == "image/jpeg") ||
            ($_FILES["file"]["type"] == "image/png") ||
            ($_FILES["file"]["type"] == "image/pjpeg")) {

            $url = 'C:/Users/admin/Downloads/compressed.jpg';
            $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
        }else {
            $error = "Uploaded image should be jpg or gif or png";
        <title>Php code compress the image</title>

        <div class="error">
                  if ($error) {
            <label class="error"><?php echo $error; ?></label>
           <fieldset class="well">
               <legend>Upload Image:</legend>
                   <form action="" name="img_compress" id="img_compress" method="post" enctype="multipart/form-data">
                                   <input type="file" name="file" id="file"/>
                               <input type="submit" name="submit" id="submit" class="submit btn-success"/>

The PHP code is beneficial in decreasing the file size of image, while uploading it to save your valuable time.

60 Responses so far.

  1. Ruby says:
    I have successfully reduced the image file size before uploading to my website, this php code worked finely. Thanks for this.
  2. Ashok Patel says:
    Nice post! I was searching for How to Compress Image File Size Using PHP code and finally got a solution. Thanks it helped me a lot to compress my image file size in php and now I uploaded it in my website.
  3. Krish says:
    Interesting article and worked successfully for my website, helped me to reduce image file size using php code, can you provide the same for video compression?
  4. peter says:
    Informative post for who wants to compress the image file size in php.
  5. Dheepan DIna says:
    Good scritpt for compressing the image file size while uploading to the website using php code. As this script does not contains any js files, this was very helpful because we only uses php code for work.
  6. sathick says:
    Thank you for the great Php code script. This article would be help full for all who is finding it difficult to reduce image file size in php for their website..
  7. Aaslin says:
    I was a java programmer and presently started to work in PHP.. This article helped me a lot to compress image file size in php for my website using this source code.
  8. selina says:
    This code worked finely for me thanks for the blog to reduce the image file size.
  9. vivek says:
    Thanks for the Php code, its working fine and helped me to compress image file size for my website.
  10. G. Putra says:
    Thank you for the code, its awesome code. I would like to use it in future my application
  11. Aparna says:
    Thanks for the php script to reduce the image file size. It helped for my website to optimize my speed too as i compressed the image file size and then uploaded in my website.
  12. Aliens says:
    Very helpful while searching around to compress images so your website loads fast and don’t visitors keep wait long. Very nice research n doing.
    its Woo PHP image code
  13. Plexure says:
    Good php script for reducing the image file size with php , but can you suggest the same using javascript?
  14. Phorani says:
    I am new to PHP and was feeling difficult to resize the image while uploading it, at the right time found a simple code and useful article which helped me to compress image file size using PHP while uploading to my website. This worked great! Thank you
  15. Joyce says:
    Good blog on compressing the image file size while uploading to your website using PHP code. Expecting more useful article likewise. I am following all your posts you put on your blog. Keep up the work going.
  16. Angelia says:
    i was searching for this query for long time , executed some codes, but i had no right solution. Let me try out this for reducing image file size while uploading it to website and check whether this is working fine for me..
  17. Henry says:
    I will give it a try. Was looking for this image compression function for uploading it in my website.
  18. Malik says:
    What is the use of reducing or compressing image file size while you upload it your website? As i am not aware of this topic i am keeping this question in front.
  19. Della says:
    Reducing image file size is an difficult one or what?? Why to use PHP code for compressing image size? can some one explain this as i am not aware of.
  20. Ganesh Rahul says:
    Nice Post. Can you give me a code to convert any image to .webp format?
    I have tried with ‘imagewebp();’

    I have error while using this,
    Fatal error: Uncaught Error: Call to undefined function imagewebp().

    I have XAMPP for Linux 7.0.8*
    And enabled with GD Support.

    I want to enable webp support.
    What I want to do?
    Can you help me out

  21. It’s nice solution for 2-3 mb images to use the PHP GD library but if you have high traffic and thousands of users uploading you will suffer.. I have expirienced it myself. We swiched the model to compress/resize images on client browser with HTML5 Canvas resize and than send it to server as Base64 string. The server uses GD just to store it az JPG. Just my experience.
  22. Eliza says:
    Good post on reducing the image file size while you upload to your website. Keep the good work.
  23. Jason says:
    I have been browsing online greater than three hours nowadays, but I by no means
    found any interesting article like yours. It’s pretty price sufficient for me.
    In my opinion, if all webmasters and bloggers made excellent content as you
    did, the net will likely be a lot more helpful than ever before.
  24. Jane says:
    Compressing image file size is really very simple using this PHP code. I would recommend others to try out this code too for their website before they upload images .
  25. Chandrasena says:
    can i know what is the use of reducing or compressing image file size when uploading to website??
  26. BeaGBockrath says:
    Good post. I learn something totally new and challenging on blogs I
    stumbleupon every day. It’s always helpful to
    read articles from other authors and use a
    little something from other websites.
  27. DorrisQLakin says:
    I feel this is one of the a great deal important information to me.
    And i am glad reading your article on how to reduce image file size. However should
    statement on few normal issues, The website style is
    perfect, the articles is truly nice : D. Good activity,
  28. JaeYKapsos says:
    Great post on reducing image size using php! We are going to be linking to the great content
    on our site. Maintain the great writing.
  29. LanetteIHitt says:
    Great article! We shall be linking to this great content on our website.
    Continue the excellent writing.
  30. TrumanXZeger says:
    Good post but I was wondering if you could write a litte more on this
    subject? I’d be very grateful if you could elaborate a little bit
    more. Bless you!
  31. Sumit says:
    Good script! I used this script and its successfully compress the image file. But png image will not open after compression because the type of png image is remain Jpeg. Please give the solution for same.


  32. jmruas says:
    After creating a file pasting the full code and sending it to the server, it gives an error “The requested URL /xxxx.php was not found on this server.”. Can you help, please?
  33. Mitchell says:
    Very descriptive post, I liked that bit.Will you keep posting more blogs about PHP?
  34. Veerapandiyan says:
    it is working fine, but i can’t save multiple files what to do please help me
  35. Myrtis Oshey says:
    nice article.I really enjoyed it.This entire blog is so interesting.I am looking forward to have more stuffs from PHP.
  36. 79Keri says:
    I must say you have hi quality articles here. Your coding for PHP compression is so awesome.looking for more blog about PHP from you.
  37. Clare Stroer says:
    Sweet blog.I really loved it.The entire blog is so awesome now i have a conclusion about reducing image size after reading this blog.
  38. Ezequiel says:
    Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to figure out if its a proble on my end or if it’s the blog.

    Any responses would be greatly appreciated.

  39. Carson Sciallo says:
    Hi, great info about how to reduce image file size using PHP Code.Looking forward to more great stuff from you!
  40. اخبار الاهلى المصرى اليوم says:
    Hello,I read your blogs named “How to Reduce or Compress Image File Size while Uploading Using PHP code? clones Info” like every week.Your writing style is witty, keep it up!
  41. Manikandan says:

    how to acheive this with multiple image upload in php. i just need to compress image and move to uploaded folder

  42. Maurice says:
    There’s definitely a lot to learn about How to Reduce or Compress Image File Size while Uploading Using PHP code.I like all of the points you have made.Thanks keep posting more blogs.
  43. Ann Weaver says:
    I came to read your blog on How to Reduce or Compress Image File Size while Uploading Using PHP code? i got a clear idea about image compression using PHP code after reading this above blog.Thanks !
  44. That is a great tip especially to compress image file size using PHP code.Simple but very accurate info.Appreciate your sharing this one.A must read article!
  45. praveen says:
    very useful ! Thanks for sharing such a useful content about reducing image file size using PHP code.
  46. Daniel says:
    Great blog mate. Thanks for sharing this useful information about image compression
  47. Sarah Carlson says:
    Good and nice blog post. it is very useful for my project,thanks for sharing your views and ideas about Image Compression using PHP Code.
  48. FirstCooper says:
    Hi, you have given really informative post about Image Compression using PHP Code.Thanks for sharing this post to our vision.
  49. Andrea Gibson says:
    Your information about PHP image compression is useful for me to know more technical information. Really very informative post you shared here. Keep sharing this type of informative blog.
  50. JannetteX says:
    Thanks for taking time to share this post.It is really useful.Continue sharing more like this.
  51. FirstLorenzo says:
    Wonderful Blog!!! Your post is very informative about Image compression.Thank you for sharing the article with us.
  52. Yetta says:
    I read your articles very excellent and i agree our all points because all is very good information provided this through in the post.
  53. Julius says:
    Really Good article.provided a helpful information.keep updating more
  54. Andrea Gibson says:
    Great Article About Image compression using PHP 🙂 It Really works very well ! keep posting such blogs 🙂
  55. tanjungpinang says:
    Does these PHP codes Really works?? its Showing error during compression
  56. Erma Bowman says:
    Excellent Blog About Image compression using PHP code.Very useful for my project
  57. nisya ahmad instagram pikore says:
    This is the block i am looking for 🙂 Thanks For your blog about image file size compression using PHP code.
  58. chocopie says:
    There is definately a great deal to know about this topic. I really like all the points you have made.
  59. chocopie says:
    NWxe7s Thanks-a-mundo for the blog post.Really looking forward to read more. Will read on
  60. chocopie says:
    cttpsR Where can I contact your company if I need some help?

Leave a Reply to chocopie Cancel reply