SlideShare a Scribd company logo
1 of 57
Download to read offline
Image Optimization:
         9 best practices
         (and some tools)

         Stoyan Stefanov, Yahoo!
         php|works + PyWorks, Atlanta, 2008




Page 1
About the presenter
         •   Exceptional Performance
         •   http://developer.yahoo.com
         •   YSlow 2.0: architect, dev
         •   Smush.it: http://smush.it
         •   Blog: http://phpied.com




Page 2
Best practices
         –   Choose PNG over GIF
         –   Crush PNGs
         –   Strip JPEG metadata
         –   Optimize GIF animations
         –   Try PNG8
         –   Avoid AlphaImageLoader
         –   Crush dynamic images
         –   Make favicons small and cacheable
         –   Use CSS sprites



Page 3
Hmm, images?
Q: Is this really
   important?
A: Let’s survey
   the global
   top 10 sites.
What % of page weight is images?
         1    Yahoo!      29%
         2    Google      75%
                                • Average

                                  45.6%
         3    YouTube     62%
         4    Live.com    64%
         5    MSN         41%
                                • Not exactly half, but
         6    MySpace     48%
                                  pretty close
         7    Wikipedia   39%
                                • Your site may be
         8    Facebook    35%     different, amazon.com
         9    Blogger     27%     for example is 71%
         10   Yahoo! JP   36%     images
                                • huge potential
Page 5
LOS
                                   SLE
                                      SS!


         #1: Choose PNG over GIF




Page 6
GIF vs. PNG
                              GIF         Palette PNG    Truecolor
                                           (aka PNG8,       PNG
                                          aka indexed)
         Number of      256              256           Up to 48bit
         colors
         Transparency   Boolean          Alpha          Alpha
                        (on/off)         (variable) *   (variable) *
         Browser        Nearly all       All A-grade    All A-grade
         support                         (96%+)         (96%+)
         Animation      Yes              No             No
                                         (future)       (future)

                * some IE < v.7 issues

Page 7
PNG transparency and IE
           Truecolor PNG
       IE 7 and up   IE 6 and earlier




                 PNG8
       IE 7 and up   IE 6 and earlier
GIF vs. PNG
         • Verdict: IE7+ is OK; IE6 supports GIF-like
           transparency
         • PNG8 can do everything a GIF can do, and more
           (sans cheesy Web 1.0 animations)
         • PNG8 works across all A-Grade browsers


         Q: And what about the size?
         A: Let’s survey the top 10 sites and
           convert all GIFs to PNGs to check if there are
           savings


Page 9
GIF-to-PNG
      1     Yahoo!         9.55%
      2     Google        22.95%
                                   • Average
      3     YouTube       33.82%
      4
      5
            Live.com
            MSN
                          19.93%
                          13.53%
                                     20.42%
      6
      7
            MySpace
            Wikipedia
                          17.65%
                        No GIFs!
                                     savings
      8     Facebook      17.47%
      9     Blogger       24.27%
      10    Yahoo! JP     24.58%


Page 10
LOS
                                   SLE
                                      SS!


          #2: Crush your PNGs




Page 11
About the PNG chunks
          •   PNGs store information in quot;chunksquot;
          •   Most chunks can safely be deleted
          •   Most image programs DO NOT optimize
          •   Command line tools:
              –   pngcrush http://pmt.sourceforge.net/pngcrush/
              –   pngrewrite http://www.pobox.com/~jason1/pngrewrite/
              –   OptiPNG http://www.cs.toronto.edu/~cosmin/pngtech/optipng/
              –   PNGOut http://advsys.net/ken/utils.htm
          • Example:
            > pngcrush -rem alla -brute -reduce
              src.png dest.png


Page 12
Crush top 10 and check for savings
      1     Yahoo!           15.52%
      2     Google Reader    22.60%
                                      • Average
      3     YouTube          17.32%
      4
      5
            Live.com
            MSN
                            No PNGs
                            No PNGs
                                        16.05%
      6
      7
            MySpace
            Wikipedia
                             25.44%
                             21.32%
                                        savings
      8     Facebook          9.08%
      9     Blogger           1.07%
      10    Yahoo! JP       No PNGs


Page 13
LOS
                                    SLE
                                       SS!


          #3: Strip JPEG metadata




Page 14
JPEG metadata
          • Comments
          • EXIF
             –   camera information
             –   thumbnail!
             –   audio!?!
             –   …
          • Application specific (e.g. Photoshop)




Page 15
Lossless JPEG operations
          •   jpegtran (http://jpegclub.org/)
          •   Free command-line tool
          •   Loseless operations such as crop, rotate
          •   You probably have it installed already

          Example:
          > jpegtran -copy none -optimize src.jpg
            dest.jpg

          -progressive?


Page 16
“baseline” JPEG - 1




Page 17
“baseline” JPEG - 2




Page 18
“baseline” JPEG - 3




Page 19
Progressive loading - 1




Page 20
Progressive loading - 2




Page 21
Progressive loading - 3




Page 22
Experiment: jpegtran and 10360 images

          • Using Yahoo Image Search API
          • Download 12000 images – query: “monkeys”,
            “babies”, “flowers”, “kittens”…
          • Cleanup 4xx responses and incorrect file types
          • Run jpegtran
             – with –optimize flag
             – with –progressive flag




Page 23
Running jpegtran on 10360 images
          • Stats:
             – The average JPEG on the web today is 52.07K
               (median size)
             – Can be optimized to 47.36K or    9.04%
             –   Converted to progressive is 46.11K or 11.45%




Page 24
Progressive vs. optimized baseline
            8000

            7000

            6000

            5000

            4000

            3000

            2000

            1000

              0

           -1000

           -2000
                   0      50000         100000
           -3000




Page 25
Progressive vs. optimized baseline
           2000



           1500



           1000



            500



              0



            -500   0   10000   20000     30000

           -1000




Page 26
Progressive vs. optimized baseline
          • Progressive is usually* better for bigger** images
          • Baseline is better for thumbs

          • * usually = 84%
          • ** bigger = 10K and over

          • This is just the trendline
          • If offline and don’t care about consistency, try
            both (“bruteforce”)



Page 27
In any event…

          •
              You can strip out   ~10%   of your JPEGs
          • with no quality loss




Page 28
LOS
                                  SLE
                                        SS!


          #4: Optimize GIF animations




Page 29
Animated GIFs
          • Some pixels don’t change from one frame to the
            other
          • Make them transparent
          • gifsicle – http://www.lcdf.org/gifsicle

          > gifsicle o2 source.gif > dest.gif




Page 30
Review
          1. Convert GIFs to PNG
          2. Crush PNGs
                                     a.k.a….
          3. Strip JPEG metadata
            Try progressive JPEG
          • Optimize animated GIFs




Page 31
#5: Make all PNGs palette PNGs *

      * but visually check the result
        (or wait for someone to complain, chances are you'll
         be waiting in vain ;)


Page 32
Truecolor vs. palette PNGs
          • Palette PNGs (PNG8) have 256 colors
          • Truecolor PNGs could have millions
          • In practice, truecolor PNGs often have less than
            1000 colors
          • Otherwise it would mean they are photos and
            should be JPEGs
          • Human eye is not that sensitive




Page 33
Truecolor vs. palette PNGs
          • Convert truecolor to palette
          • How about 50% savings?
          • Solves IE<7’s little alpha transparency problem




          • Warning 1: LOSSY
             – But no one will ever know
          • Warning 2: automation is hard when there’s alpha



Page 34
Truecolor vs. palette PNGs
          Command-line tools:
          • pngquant (http://www.libpng.org/pub/png/apps/pngquant.html)
          • pngnq (http://pngnq.sourceforge.net/)


          Example:
          > pngquant 256 src.png




Page 35
#6: Avoid AlphaImageLoader




Page 36
CSS filters
          • Back to the problem with truecolor PNG alpha
            transparency in earlier IEs
          • AlphaImageLoader CSS filter to fix the issue

          #mydiv {
            background: url(image.png);
            _background: none;
            _filter:progid:DXImageTransform.Microsoft.AlphaImageLoader
                     (src='image.png', sizingMethod='crop');
          }




Page 37
CSS filters problems
          •   IE proprietary
          •   Blocks rendering, freezes the browser
          •   Increased memory consumption
          •   Per element, not per image!
          •   CSS code for sprites becomes messy




Page 38
Avoid filters
          • Best: Avoid completely, use gracefully degrading
            PNG8
          • Fallback: use underscore hack _filter not to
            penalize IE7+ users



          • Yahoo! Search saved 50-100ms for users of IE5&6




Page 39
LOS
                                 SLE
                                     SS!


          #7: Crush dynamic images




Page 40
Dynamically generated images
          • GD library doesn't do what pngcrush does
          • Generated images are bigger
          • From big to small:
            generated GIF > generated PNG > crushed PNG
          • Server resources on every request




Page 41
Recipe for generated images
          1st request:
          • generate        • Estimate

                              5-30%
          • write to disk
          • pngcrush
          • serve
          2nd request:
          • serve cached
                              savings

Page 42
Case study: Google charts API


          Original (707 colors) Crushed (707 colors) PNG8 (256 colors)




                               12% saving           38% saving




Page 43
Case study: Google charts API

          Original (1408 colors) Crushed (1408 colors) PNG8 (256 colors)




                                25% saving            55% saving
                                                      (1000+ colors are
                                                      lost but who can
                                                      tell?)


Page 44
#8: Make favicon smaller




Page 45
favicon.ico
          • www.example.org/favicon.ico
             – The browser will request it
             – Better not respond with a 404
             – Cookies are sent
             – Cannot be on CDN
             – Interferes with the download sequence
          • Make it small (<= 1K)
          • Set Expires header (but not “forever”)

          <link rel=quot;shortcut iconquot;…> ???




Page 46
favicon.ico
          • Tools: imagemagick, png2ico
          • Case study: Yahoo! Search - favicon.ico is 9% of all page
            views




Page 47
#9: Use CSS sprites




Page 48
CSS Sprites




          CSS:



                        …

      HTML:




Page 49
CSS Sprites
          • Size of the combined image is usually less
          • You save HTTP requests
          • Articles:
             http://alistapart.com/articles/sprites
             http
            ://css-tricks.com/css-sprites-what-they-are-why-theyre




Page 50
Optimizing sprites




Page 51
Optimize CSS sprites
          • Avoid gaps
          • Stay within the 256 colors of PNG8




Page 52
CSS sprites
          • Creating…
          • Maintaining…
          • … is a pain



          But there are tools:
          - http://csssprites.com
          - http://spritegen.website-performance.org




Page 53
Wrapping up




          You can save 10-30% in
            unnecessary image size!




Page 54
Thank you!




               slides…


Page 55
Slides and other URLs
          •   Slides: http://slideshare.net/stoyan
          •   Blog: http://phpied.com
          •   Img opt series: http://www.yuiblog.com/
          •   Tool: http://smush.it
          •   Yahoo! http://developer.yahoo.com/performance




Page 56
Credits
          •   http://svs.gsfc.nasa.gov/vis/a000000/a002600/a002680/ Apolo 17 Full-Earth Photograph
          •   http://www.w3.org/Graphics/PNG/inline-alpha.html W3C PNG Alpha Test
          •   http://www.sitepoint.com/blogs/2007/09/18/png8-the-clear-winner/ PNG8 - The Clear Winner




Page 57

More Related Content

Viewers also liked

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureDan McKinley
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeperSaurav Haloi
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcachedJurriaan Persyn
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsJonas Bonér
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApartTellApart
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 
The Physics of Fast Image Compression
The Physics of Fast Image CompressionThe Physics of Fast Image Compression
The Physics of Fast Image CompressionCloudinary
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparReact London Community
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging ChallengesAaron Irizarry
 

Viewers also liked (17)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds Architecture
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Intro to HBase
Intro to HBaseIntro to HBase
Intro to HBase
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
 
Endocarditis
EndocarditisEndocarditis
Endocarditis
 
Apache Spark Architecture
Apache Spark ArchitectureApache Spark Architecture
Apache Spark Architecture
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApart
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
The Physics of Fast Image Compression
The Physics of Fast Image CompressionThe Physics of Fast Image Compression
The Physics of Fast Image Compression
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor Charypar
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging Challenges
 

Similar to Image Optimization for the Web at php|works

Yahoo - Web Images optimization
Yahoo - Web Images optimizationYahoo - Web Images optimization
Yahoo - Web Images optimizationEduard Bondarenko
 
Images - 7 mistakes (first draft)
Images - 7 mistakes (first draft)Images - 7 mistakes (first draft)
Images - 7 mistakes (first draft)Stoyan Stefanov
 
Imagecon 2019 - Jon Sneyers
Imagecon 2019 - Jon Sneyers Imagecon 2019 - Jon Sneyers
Imagecon 2019 - Jon Sneyers Cloudinary
 
Pinax Presentation at DjangoCon 2008
Pinax Presentation at DjangoCon 2008Pinax Presentation at DjangoCon 2008
Pinax Presentation at DjangoCon 2008jtauber
 
Voices that matter: High Performance Web Sites
Voices that matter: High Performance Web SitesVoices that matter: High Performance Web Sites
Voices that matter: High Performance Web SitesStoyan Stefanov
 
Mo devtablet johncromartie-graphicsperformance
Mo devtablet johncromartie-graphicsperformanceMo devtablet johncromartie-graphicsperformance
Mo devtablet johncromartie-graphicsperformancejohncromartie
 
Integrating with the Photography Ecosystem on Mac OS X
Integrating with the Photography Ecosystem on Mac OS XIntegrating with the Photography Ecosystem on Mac OS X
Integrating with the Photography Ecosystem on Mac OS Xfraserspeirs
 
Performance as UX with Justin Howlett
Performance as UX with Justin HowlettPerformance as UX with Justin Howlett
Performance as UX with Justin HowlettFITC
 
Improving Drupal's Page Loading Performance
Improving Drupal's Page Loading PerformanceImproving Drupal's Page Loading Performance
Improving Drupal's Page Loading PerformanceWim Leers
 
Ignite Velocity: Image Weight Loss Clinic
Ignite Velocity: Image Weight Loss ClinicIgnite Velocity: Image Weight Loss Clinic
Ignite Velocity: Image Weight Loss ClinicStoyan Stefanov
 
We should optimize images
We should optimize imagesWe should optimize images
We should optimize imagesShogo Sensui
 
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)Guy Podjarny
 
Dont turn your photoshop off
Dont turn your photoshop offDont turn your photoshop off
Dont turn your photoshop offIgor Napierala
 
Building Twitter in Drupal
Building Twitter in DrupalBuilding Twitter in Drupal
Building Twitter in DrupalJeff Eaton
 

Similar to Image Optimization for the Web at php|works (20)

Yahoo - Web Images optimization
Yahoo - Web Images optimizationYahoo - Web Images optimization
Yahoo - Web Images optimization
 
Images - 7 mistakes (first draft)
Images - 7 mistakes (first draft)Images - 7 mistakes (first draft)
Images - 7 mistakes (first draft)
 
Images - 7 mistakes
Images - 7 mistakesImages - 7 mistakes
Images - 7 mistakes
 
Imagecon 2019 - Jon Sneyers
Imagecon 2019 - Jon Sneyers Imagecon 2019 - Jon Sneyers
Imagecon 2019 - Jon Sneyers
 
Pinax Presentation at DjangoCon 2008
Pinax Presentation at DjangoCon 2008Pinax Presentation at DjangoCon 2008
Pinax Presentation at DjangoCon 2008
 
Pinax
PinaxPinax
Pinax
 
Voices that matter: High Performance Web Sites
Voices that matter: High Performance Web SitesVoices that matter: High Performance Web Sites
Voices that matter: High Performance Web Sites
 
Image Optimization for The Web
Image Optimization for The WebImage Optimization for The Web
Image Optimization for The Web
 
Mo devtablet johncromartie-graphicsperformance
Mo devtablet johncromartie-graphicsperformanceMo devtablet johncromartie-graphicsperformance
Mo devtablet johncromartie-graphicsperformance
 
Integrating with the Photography Ecosystem on Mac OS X
Integrating with the Photography Ecosystem on Mac OS XIntegrating with the Photography Ecosystem on Mac OS X
Integrating with the Photography Ecosystem on Mac OS X
 
Performance as UX with Justin Howlett
Performance as UX with Justin HowlettPerformance as UX with Justin Howlett
Performance as UX with Justin Howlett
 
PNGHack 1.0 Presentation
PNGHack 1.0 PresentationPNGHack 1.0 Presentation
PNGHack 1.0 Presentation
 
Improving Drupal's Page Loading Performance
Improving Drupal's Page Loading PerformanceImproving Drupal's Page Loading Performance
Improving Drupal's Page Loading Performance
 
Ignite Velocity: Image Weight Loss Clinic
Ignite Velocity: Image Weight Loss ClinicIgnite Velocity: Image Weight Loss Clinic
Ignite Velocity: Image Weight Loss Clinic
 
We should optimize images
We should optimize imagesWe should optimize images
We should optimize images
 
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)
High Performance Images: Beautiful Shouldn't Mean Slow (Velocity EU 2015)
 
After YSlow "A"
After YSlow "A"After YSlow "A"
After YSlow "A"
 
Design Fast Websites
Design Fast WebsitesDesign Fast Websites
Design Fast Websites
 
Dont turn your photoshop off
Dont turn your photoshop offDont turn your photoshop off
Dont turn your photoshop off
 
Building Twitter in Drupal
Building Twitter in DrupalBuilding Twitter in Drupal
Building Twitter in Drupal
 

More from Stoyan Stefanov

JavaScript Performance Patterns
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance PatternsStoyan Stefanov
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patternsStoyan Stefanov
 
High Performance Social Plugins
High Performance Social PluginsHigh Performance Social Plugins
High Performance Social PluginsStoyan Stefanov
 
JavaScript навсякъде
JavaScript навсякъдеJavaScript навсякъде
JavaScript навсякъдеStoyan Stefanov
 
JavaScript is everywhere
JavaScript is everywhereJavaScript is everywhere
JavaScript is everywhereStoyan Stefanov
 
JavaScript shell scripting
JavaScript shell scriptingJavaScript shell scripting
JavaScript shell scriptingStoyan Stefanov
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2Stoyan Stefanov
 
Progressive Downloads and Rendering
Progressive Downloads and RenderingProgressive Downloads and Rendering
Progressive Downloads and RenderingStoyan Stefanov
 
Psychology of performance
Psychology of performancePsychology of performance
Psychology of performanceStoyan Stefanov
 
CSS and image optimization
CSS and image optimizationCSS and image optimization
CSS and image optimizationStoyan Stefanov
 
High-performance DOM scripting
High-performance DOM scriptingHigh-performance DOM scripting
High-performance DOM scriptingStoyan Stefanov
 
The business of performance
The business of performanceThe business of performance
The business of performanceStoyan Stefanov
 

More from Stoyan Stefanov (20)

Reactive JavaScript
Reactive JavaScriptReactive JavaScript
Reactive JavaScript
 
YSlow hacking
YSlow hackingYSlow hacking
YSlow hacking
 
Liking performance
Liking performanceLiking performance
Liking performance
 
JavaScript Performance Patterns
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance Patterns
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patterns
 
High Performance Social Plugins
High Performance Social PluginsHigh Performance Social Plugins
High Performance Social Plugins
 
Social Button BFFs
Social Button BFFsSocial Button BFFs
Social Button BFFs
 
JavaScript навсякъде
JavaScript навсякъдеJavaScript навсякъде
JavaScript навсякъде
 
JavaScript is everywhere
JavaScript is everywhereJavaScript is everywhere
JavaScript is everywhere
 
JavaScript shell scripting
JavaScript shell scriptingJavaScript shell scripting
JavaScript shell scripting
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
WPO @ PubCon 2010
WPO @ PubCon 2010WPO @ PubCon 2010
WPO @ PubCon 2010
 
Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2
 
Progressive Downloads and Rendering
Progressive Downloads and RenderingProgressive Downloads and Rendering
Progressive Downloads and Rendering
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Psychology of performance
Psychology of performancePsychology of performance
Psychology of performance
 
3-in-1 YSlow
3-in-1 YSlow3-in-1 YSlow
3-in-1 YSlow
 
CSS and image optimization
CSS and image optimizationCSS and image optimization
CSS and image optimization
 
High-performance DOM scripting
High-performance DOM scriptingHigh-performance DOM scripting
High-performance DOM scripting
 
The business of performance
The business of performanceThe business of performance
The business of performance
 

Recently uploaded

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 

Recently uploaded (20)

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 

Image Optimization for the Web at php|works

  • 1. Image Optimization: 9 best practices (and some tools) Stoyan Stefanov, Yahoo! php|works + PyWorks, Atlanta, 2008 Page 1
  • 2. About the presenter • Exceptional Performance • http://developer.yahoo.com • YSlow 2.0: architect, dev • Smush.it: http://smush.it • Blog: http://phpied.com Page 2
  • 3. Best practices – Choose PNG over GIF – Crush PNGs – Strip JPEG metadata – Optimize GIF animations – Try PNG8 – Avoid AlphaImageLoader – Crush dynamic images – Make favicons small and cacheable – Use CSS sprites Page 3
  • 4. Hmm, images? Q: Is this really important? A: Let’s survey the global top 10 sites.
  • 5. What % of page weight is images? 1 Yahoo! 29% 2 Google 75% • Average 45.6% 3 YouTube 62% 4 Live.com 64% 5 MSN 41% • Not exactly half, but 6 MySpace 48% pretty close 7 Wikipedia 39% • Your site may be 8 Facebook 35% different, amazon.com 9 Blogger 27% for example is 71% 10 Yahoo! JP 36% images • huge potential Page 5
  • 6. LOS SLE SS! #1: Choose PNG over GIF Page 6
  • 7. GIF vs. PNG GIF Palette PNG Truecolor (aka PNG8, PNG aka indexed) Number of 256 256 Up to 48bit colors Transparency Boolean Alpha Alpha (on/off) (variable) * (variable) * Browser Nearly all All A-grade All A-grade support (96%+) (96%+) Animation Yes No No (future) (future) * some IE < v.7 issues Page 7
  • 8. PNG transparency and IE Truecolor PNG IE 7 and up IE 6 and earlier PNG8 IE 7 and up IE 6 and earlier
  • 9. GIF vs. PNG • Verdict: IE7+ is OK; IE6 supports GIF-like transparency • PNG8 can do everything a GIF can do, and more (sans cheesy Web 1.0 animations) • PNG8 works across all A-Grade browsers Q: And what about the size? A: Let’s survey the top 10 sites and convert all GIFs to PNGs to check if there are savings Page 9
  • 10. GIF-to-PNG 1 Yahoo! 9.55% 2 Google 22.95% • Average 3 YouTube 33.82% 4 5 Live.com MSN 19.93% 13.53% 20.42% 6 7 MySpace Wikipedia 17.65% No GIFs! savings 8 Facebook 17.47% 9 Blogger 24.27% 10 Yahoo! JP 24.58% Page 10
  • 11. LOS SLE SS! #2: Crush your PNGs Page 11
  • 12. About the PNG chunks • PNGs store information in quot;chunksquot; • Most chunks can safely be deleted • Most image programs DO NOT optimize • Command line tools: – pngcrush http://pmt.sourceforge.net/pngcrush/ – pngrewrite http://www.pobox.com/~jason1/pngrewrite/ – OptiPNG http://www.cs.toronto.edu/~cosmin/pngtech/optipng/ – PNGOut http://advsys.net/ken/utils.htm • Example: > pngcrush -rem alla -brute -reduce src.png dest.png Page 12
  • 13. Crush top 10 and check for savings 1 Yahoo! 15.52% 2 Google Reader 22.60% • Average 3 YouTube 17.32% 4 5 Live.com MSN No PNGs No PNGs 16.05% 6 7 MySpace Wikipedia 25.44% 21.32% savings 8 Facebook 9.08% 9 Blogger 1.07% 10 Yahoo! JP No PNGs Page 13
  • 14. LOS SLE SS! #3: Strip JPEG metadata Page 14
  • 15. JPEG metadata • Comments • EXIF – camera information – thumbnail! – audio!?! – … • Application specific (e.g. Photoshop) Page 15
  • 16. Lossless JPEG operations • jpegtran (http://jpegclub.org/) • Free command-line tool • Loseless operations such as crop, rotate • You probably have it installed already Example: > jpegtran -copy none -optimize src.jpg dest.jpg -progressive? Page 16
  • 23. Experiment: jpegtran and 10360 images • Using Yahoo Image Search API • Download 12000 images – query: “monkeys”, “babies”, “flowers”, “kittens”… • Cleanup 4xx responses and incorrect file types • Run jpegtran – with –optimize flag – with –progressive flag Page 23
  • 24. Running jpegtran on 10360 images • Stats: – The average JPEG on the web today is 52.07K (median size) – Can be optimized to 47.36K or 9.04% – Converted to progressive is 46.11K or 11.45% Page 24
  • 25. Progressive vs. optimized baseline 8000 7000 6000 5000 4000 3000 2000 1000 0 -1000 -2000 0 50000 100000 -3000 Page 25
  • 26. Progressive vs. optimized baseline 2000 1500 1000 500 0 -500 0 10000 20000 30000 -1000 Page 26
  • 27. Progressive vs. optimized baseline • Progressive is usually* better for bigger** images • Baseline is better for thumbs • * usually = 84% • ** bigger = 10K and over • This is just the trendline • If offline and don’t care about consistency, try both (“bruteforce”) Page 27
  • 28. In any event… • You can strip out ~10% of your JPEGs • with no quality loss Page 28
  • 29. LOS SLE SS! #4: Optimize GIF animations Page 29
  • 30. Animated GIFs • Some pixels don’t change from one frame to the other • Make them transparent • gifsicle – http://www.lcdf.org/gifsicle > gifsicle o2 source.gif > dest.gif Page 30
  • 31. Review 1. Convert GIFs to PNG 2. Crush PNGs a.k.a…. 3. Strip JPEG metadata Try progressive JPEG • Optimize animated GIFs Page 31
  • 32. #5: Make all PNGs palette PNGs * * but visually check the result (or wait for someone to complain, chances are you'll be waiting in vain ;) Page 32
  • 33. Truecolor vs. palette PNGs • Palette PNGs (PNG8) have 256 colors • Truecolor PNGs could have millions • In practice, truecolor PNGs often have less than 1000 colors • Otherwise it would mean they are photos and should be JPEGs • Human eye is not that sensitive Page 33
  • 34. Truecolor vs. palette PNGs • Convert truecolor to palette • How about 50% savings? • Solves IE<7’s little alpha transparency problem • Warning 1: LOSSY – But no one will ever know • Warning 2: automation is hard when there’s alpha Page 34
  • 35. Truecolor vs. palette PNGs Command-line tools: • pngquant (http://www.libpng.org/pub/png/apps/pngquant.html) • pngnq (http://pngnq.sourceforge.net/) Example: > pngquant 256 src.png Page 35
  • 37. CSS filters • Back to the problem with truecolor PNG alpha transparency in earlier IEs • AlphaImageLoader CSS filter to fix the issue #mydiv { background: url(image.png); _background: none; _filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (src='image.png', sizingMethod='crop'); } Page 37
  • 38. CSS filters problems • IE proprietary • Blocks rendering, freezes the browser • Increased memory consumption • Per element, not per image! • CSS code for sprites becomes messy Page 38
  • 39. Avoid filters • Best: Avoid completely, use gracefully degrading PNG8 • Fallback: use underscore hack _filter not to penalize IE7+ users • Yahoo! Search saved 50-100ms for users of IE5&6 Page 39
  • 40. LOS SLE SS! #7: Crush dynamic images Page 40
  • 41. Dynamically generated images • GD library doesn't do what pngcrush does • Generated images are bigger • From big to small: generated GIF > generated PNG > crushed PNG • Server resources on every request Page 41
  • 42. Recipe for generated images 1st request: • generate • Estimate 5-30% • write to disk • pngcrush • serve 2nd request: • serve cached savings Page 42
  • 43. Case study: Google charts API Original (707 colors) Crushed (707 colors) PNG8 (256 colors) 12% saving 38% saving Page 43
  • 44. Case study: Google charts API Original (1408 colors) Crushed (1408 colors) PNG8 (256 colors) 25% saving 55% saving (1000+ colors are lost but who can tell?) Page 44
  • 45. #8: Make favicon smaller Page 45
  • 46. favicon.ico • www.example.org/favicon.ico – The browser will request it – Better not respond with a 404 – Cookies are sent – Cannot be on CDN – Interferes with the download sequence • Make it small (<= 1K) • Set Expires header (but not “forever”) <link rel=quot;shortcut iconquot;…> ??? Page 46
  • 47. favicon.ico • Tools: imagemagick, png2ico • Case study: Yahoo! Search - favicon.ico is 9% of all page views Page 47
  • 48. #9: Use CSS sprites Page 48
  • 49. CSS Sprites CSS: … HTML: Page 49
  • 50. CSS Sprites • Size of the combined image is usually less • You save HTTP requests • Articles: http://alistapart.com/articles/sprites http ://css-tricks.com/css-sprites-what-they-are-why-theyre Page 50
  • 52. Optimize CSS sprites • Avoid gaps • Stay within the 256 colors of PNG8 Page 52
  • 53. CSS sprites • Creating… • Maintaining… • … is a pain But there are tools: - http://csssprites.com - http://spritegen.website-performance.org Page 53
  • 54. Wrapping up You can save 10-30% in unnecessary image size! Page 54
  • 55. Thank you! slides… Page 55
  • 56. Slides and other URLs • Slides: http://slideshare.net/stoyan • Blog: http://phpied.com • Img opt series: http://www.yuiblog.com/ • Tool: http://smush.it • Yahoo! http://developer.yahoo.com/performance Page 56
  • 57. Credits • http://svs.gsfc.nasa.gov/vis/a000000/a002600/a002680/ Apolo 17 Full-Earth Photograph • http://www.w3.org/Graphics/PNG/inline-alpha.html W3C PNG Alpha Test • http://www.sitepoint.com/blogs/2007/09/18/png8-the-clear-winner/ PNG8 - The Clear Winner Page 57