PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

[FIXED] How to optimize images in PHP?

 October 11, 2022     gd, image-processing, imagemagick, php     No comments   

Issue

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

Possible:

  • convert it to GIF
  • Color fill to transparent PNGs

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

Thanks a lot!


Solution

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.



Answered By - John Green
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing