How to optimize images in PHP?

I've a website where users can save their profile image (avatar).

I'd like to make some optimization to the image when they load it.

I mean, it's an avatar image, doesn't need full resolution, nor great size.

What can i do? I've been thinking:

  • Resize it
  • Low the quality


  • convert it to GIF
  • Color fill to transparent PNGs

There are some library better (simpler) than GD to do this?

Thanks a lot!

-------------Problems Reply------------

GD is how this is done. It sounds like a simple operation, but there are a number of factors that you really want to get right if you're going to do this. All in all, this winds up being several hundred lines of code to take care of everything.

My recommendation is that although you may wish to resize an image (which requires a lossy recompression if using JPEG), converting it to a GIF is a bad idea. You don't know what the source type is, so doing that is problematic.

Here's my recommended flow:

1) Resize the image to your output format. You can force a cropping aspect ratio here as well, if you want.

2) Determine original source mode:

  • 8 bit indexed (GIF/PNG8): Save as PNG8 (format tends to be smaller than GIF).
  • 16-24 bit: Save as JPG. Quality is up to you, but 70% is a good baseline.
  • 32 bit (PNG24): Save as PNG24, taking care to maintain the transparency.

Note, this solution pretty much destroys any 'animated' gifs, but... that's what happens when you try to resize an animated gif.

Although... I also highly recommend to NOT do this as a single stage process and removing the original files. This is the kind of thing that will only come back to bite you later.

Disk space is cheap these days... far better to store the original in a high quality format (even at 2K x 2K resolution), then create an image service which will serve the resolution/quality you need and cache the result.

You could use the Asido imaging library for PHP to resize your images. This library makes use of GD though. Here is some example usage code.

The resizing and other imaging operations are preferably done after the uploading of new images (except if you want to save the higher resolution for some other purpose).

I'd pick some standard avatar image sizes you'll need for your page, like

  • medium size for a profile page, if you have one and
  • small size which appears next to the user's post
  • you get the idea, just what you need

And when the user uploads a new avatar, you convert it to the formats you'll need with a reasonable quality setting. I'm assuming you're going for JPEGs, because this is a good catch-all format for this use case. PNGs do poor with photographic content, JPEGs are not so great for drawings, but then most avatars you see are photos. I wouldn't use GIFs any more these days, they limit to 256 colors and have only a 1-bit alpha channel.

//This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
return false;
//Construct a proportional size of new image
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
return false;
//Destroy image, frees memory
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
return true;

Category:php Views:0 Time:2011-07-13

Related post

  • SQL 2005 Book For Optimization Techniques 2008-08-22

    My knowledge of SQL has been mostly gathered through immediate need as opposed to formal training. The project I'm working on now requires the next level of SQL (specifically SQL Server 2005) knowledge. That is, I need to know techniques for optimizi

  • Which, if any, C++ compilers do tail-recursion optimization? 2008-08-29

    It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep th

  • PDB files for production app and the "Optimize code" flag 2008-09-03

    When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception? If there is a noticeable performance benefit I would want to use the optimizations but if

  • profile-guided optimization (C) 2008-09-09

    Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops? (this question is specific, not about optimization in general, thanks) --------------Solutions----------

  • How do you normally set up your compiler's optimization settings? 2008-09-10

    Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why? I notice most of the time people tend to just leave compiler optimization settings to their def

  • Optimize Windows Form Load Time 2008-09-12

    I have a Windows Form that takes quite a bit of time to load initially. However, each subsequent request to load the Form doesn't take as long. Is there a way to optimize a Form's load time? --------------Solutions------------- You can use ngen. I al

  • Common memory optimization 2008-09-13

    What are the most common memory optimizations in csharp, dotnet 2.0. Wanted to see if there common things that people may not be doing by default in winform app --------------Solutions------------- use structs for small wrapper objects to avoid heap

  • Does Java save its runtime optimizations? 2008-09-16

    My professor did an informal benchmark on a little program and the Java times were: 1.7 seconds for the first run, and 0.8 seconds for the runs thereafter. Is this due entirely to the loading of the runtime environment into the operating environment

  • Why does a C/C++ program often have optimization turned off in debug mode? 2008-09-16

    In most C or C++ environments, there is a "debug" mode and a "release" mode compilation. Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables mo

  • Runtime Page Optimizer for - Any comments? 2008-09-17

    RPO 1.0 (Runtime Page Optimizer) is a recently (today?) released component for ASP and Sharepoint that compresses, combines and minifies (I can’t believe that is a real word) Javascript, CSS and other things. What is interesting is that it was develo

  • Do I have a gcc optimization bug or a C code problem? 2008-09-17

    Test the following code: #include <stdio.h> #include <stdlib.h> main() { const char *yytext="0"; const float f=(float)atof(yytext); size_t t = *((size_t*)&f); printf("t should be 0 but is %d\n", t); } Compile it with: gcc -O3 test.c T

  • What is the difference between gcc optimization levels? 2008-09-18

    What is the difference between different optimization levels in GCC? Assuming I don't care to have any debug hooks, why wouldn't I just use the highest level of optimization available to me? does a higher level of optimization necessarily (i.e. prova

  • AMD 64 bit Dual Core Optimization 2008-09-19

    We have a graphics intensive application that seems to be experiencing problems on AMD 64 bit Dual Core platforms that are not apparent on Intel platforms. Running the application causes the CPU to run at 100%, in particular when using code for shado

  • What are indexes and how can I use them to optimize queries in my database? 2008-09-19

    This question already has an answer here: What is an index in SQL? 10 answers I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures. I always hear that "adding an i

  • Does the JVM prevent tail call optimizations? 2008-09-19

    I saw this quote on the question: What is a good functional language on which to build a web service? Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this

  • GCC optimization flags for Intel Atom 2008-09-21

    I'm developing a performance critical application for Intel Atom processor. What are the best gcc optimization flags for this CPU? --------------Solutions------------- There is a cool framework called Acovea (Analysis of Compiler Options via Evolutio

  • Optimize y = x*x in Galois field arithmetic 2008-09-22

    I have this C-code to do multiplications over GF(8): int32_t GaloisMultiply (int32_t a, int32_t b) { int32_t i; int32_t mask = 0x100; int32_t y = 0; for(i=0;i<8;i++) { if(b & mask) { y ^= a; } mask >>= 1; y <<= 1; } if(b & 0x1)

  • Why doesn't GCC optimize structs? 2008-09-22

    Systems demand that certain primitives be aligned to certain points within the memory (ints to bytes that are multiples of 4, shorts to bytes that are multiples of 2, etc.). Of course, these can be optimized to waste the least space in padding. My qu

  • C# Compiler Incorrectly Optimizes Code 2008-09-23

    I have a ASP.NET application running on a remote web server and I just started getting this error: Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'. I disassembled the code in the DLL and it seems like the compiler is incorre

  • Last Resource Optimization 2008-09-25

    I'm writing a Resource Adaptor which does not support two phase commit. I know there is an optimization technique called: "Last Resource Optimization". On JBoss your XAResource class should implement LastResource in order to have the optimization. My

Copyright (C), All Rights Reserved.

processed in 0.128 (s). 11 q(s)