设计更快的网页（一）：图片压缩
网页
![](/data/attachment/album/201810/28/213800xzz7e7txh75t5hhl.jpg)


很多 Web 开发者都希望做出加载速度很快的网页。在移动设备浏览占比越来越大的背景下，使用响应式设计使得网站在小屏幕下看起来更漂亮只是其中一个方面。Browser Calories 可以展示网页的加载时间 —— 这不单单关系到用户，还会影响到通过加载速度来进行评级的搜索引擎。这个系列的文章介绍了如何使用 Fedora 提供的工具来给网页“瘦身”。


### 准备工作


在你开始缩减网页之前，你需要明确核心问题所在。为此，你可以使用 [Browserdiet](https://browserdiet.com/calories/). 这是一个浏览器插件，适用于 Firefox、Opera、 Chrome 和其它浏览器。它会对打开的网页进行性能分析，这样你就可以知道应该从哪里入手来缩减网页。


然后，你需要一些用来处理的页面。下面的例子是针对 [getferoda.org](http://getfedora.org) 的测试截图。一开始，它看起来非常简单，也符合响应式设计。


![Browser Diet - getfedora.org 的评分](/data/attachment/album/201810/28/213800fjped7j9c1p3ej15.jpg)


然而，BroserDiet 的网页分析表明，这个网页需要加载 1.8MB 的文件。所以，我们现在有活干了！


### Web 优化


网页中包含 281 KB 的 JavaScript 文件、203 KB 的 CSS 文件，还有 1.2 MB 的图片。我们先从最严重的问题 —— 图片开始入手。为了解决问题，你需要的工具集有 GIMP、ImageMagick 和 optipng. 你可以使用如下命令轻松安装它们：



```
sudo dnf install gimp imagemagick optipng
```

比如，我们先拿到这个 6.4 KB 的[文件](https://getfedora.org/static/images/cinnamon.png)：


![](/data/attachment/album/201810/28/213803dhjhjmcej0ccxcbc.png)


首先，使用 `file` 命令来获取这张图片的一些基本信息：



```
$ file cinnamon.png
cinnamon.png: PNG image data, 60 x 60, 8-bit/color RGBA, non-interlaced
```

这张只由白色和灰色构成的图片使用 8 位 / RGBA 模式来存储。这种方式并没有那么高效。


使用 GIMP，你可以为这张图片设置一个更合适的颜色模式。在 GIMP 中打开 `cinnamon.png`。然后，在“图片 > 模式”菜单中将其设置为“灰度模式”。将这张图片以 PNG 格式导出。导出时使用压缩因子 9，导出对话框中的其它配置均使用默认选项。



```
$ file cinnamon.png
cinnamon.png: PNG image data, 60 x 60, 8-bit gray+alpha, non-interlaced
```

输出显示，现在这个文件现在处于 8 位 / 灰阶 + aplha 模式。文件大小从 6.4 KB 缩小到了 2.8 KB. 这已经是原来大小的 43.75% 了。但是，我们能做的还有很多！


你可以使用 ImageMagick 工具来查看这张图片的更多信息。



```
$ identify cinnamon2.png
cinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2831B 0.000u 0:00.000
```

它告诉你，这个文件的大小为 2831 字节。我们回到 GIMP，重新导出文件。在导出对话框中，取消存储时间戳和 alpha 通道色值，来让文件更小一点。现在文件输出显示：



```
$ identify cinnamon.png
cinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2798B 0.000u 0:00.000
```

下面，用 `optipng` 来无损优化你的 PNG 图片。具有相似功能的工具有很多，包括 `advdef`（这是 advancecomp 的一部分），`pngquant` 和 `pngcrush`。


对你的文件运行 `optipng`。 注意，这个操作会覆盖你的原文件：



```
$ optipng -o7 cinnamon.png
** Processing: cinnamon.png
60x60 pixels, 2x8 bits/pixel, grayscale+alpha
Reducing image to 8 bits/pixel, grayscale
Input IDAT size = 2720 bytes
Input file size = 2812 bytes

Trying:
 zc = 9 zm = 8 zs = 0 f = 0 IDAT size = 1922
 zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920

Selecting parameters:
 zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920

Output IDAT size = 1920 bytes (800 bytes decrease)
Output file size = 2012 bytes (800 bytes = 28.45% decrease)
```

`-o7` 选项处理起来最慢，但最终效果最好。于是你又将文件缩小了 800 字节，现在它只有 2012 字节了。


要压缩文件夹下的所有 PNG，可以使用这个命令：



```
$ optipng -o7 -dir=<directory> *.png
```

`-dir` 选项用来指定输出文件夹。如果不加这个选项，`optipng` 会覆盖原文件。


### 选择正确的文件格式


当涉及到在互联网中使用的图片时，你可以选择：


* [JPG 或 JPEG](https://en.wikipedia.org/wiki/JPEG)
* [GIF](https://en.wikipedia.org/wiki/GIF)
* [PNG](https://en.wikipedia.org/wiki/Portable_Network_Graphics)
* [aPNG](https://en.wikipedia.org/wiki/APNG)
* [JPG-LS](https://en.wikipedia.org/wiki/JPEG_2000)
* [JPG 2000 或 JP2](https://en.wikipedia.org/wiki/JPEG_2000)
* [SVG](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics)


JPG-LS 和 JPG 2000 没有得到广泛使用。只有一部分数码相机支持这些格式，所以我们可以忽略它们。aPNG 是动态的 PNG 格式，也没有广泛使用。


可以通过更改压缩率或者使用其它文件格式来节省下更多字节。我们无法在 GIMP 中应用第一种方法，因为现在的图片已经使用了最高的压缩率了。因为我们的图片中不再包含 [aplha 通道](https://www.webopedia.com/TERM/A/alpha_channel.html)，你可以使用 JPG 类型来替代 PNG。 现在，使用默认值：90% 质量 —— 你可以将它减小至 85%，但这样会导致可见的叠影。这样又省下一些字节：



```
$ identify cinnamon.jpg
cinnamon.jpg JPEG 60x60 60x60+0+0 8-bit sRGB 2676B 0.000u 0:00.000
```

只将这张图转成正确的色域，并使用 JPG 作为文件格式，就可以将它从 23 KB 缩小到 12.3 KB，减少了近 50%.


#### PNG vs JPG: 质量和压缩率


那么，剩下的文件我们要怎么办呢？除了 Fedora “风味”图标和四个特性图标之外，此方法适用于所有其他图片。我们能够处理的图片都有一个白色的背景。


PNG 和 JPG 的一个主要区别在于，JPG 没有 alpha 通道。所以，它没有透明度选项。如果你使用 JPG 并为它添加白色背景，你可以将文件从 40.7 KB 缩小至 28.3 KB.


现在又有了四个可以处理的图片：背景图。对于灰色背景，你可以再次使用灰阶模式。对更大的图片，我们就可以节省下更多的空间。它从 216.2 KB 缩小到了 51 KB —— 基本上只有原图的 25% 了。整体下来，你把这些图片从 481.1 KB 缩小到了 191.5 KB —— 只有一开始的 39.8%.


#### 质量 vs 大小


PNG 和 JPG 的另外一个区别在于质量。PNG 是一种无损压缩光栅图形格式。但是 JPG 虽然使用压缩来缩小体积，可是这会影响到质量。不过，这并不意味着你不应该使用 JPG，只是你需要在文件大小和质量中找到一个平衡。


### 成就


这就是第一部分的结尾了。在使用上述技术后，得到的结果如下：


![](/data/attachment/album/201810/28/213804glanjnppfhchy0at.jpg)


你将一开始 1.2 MB 的图片体积缩小到了 488.9 KB. 只需通过 `optipng` 进行优化，就可以达到之前体积的三分之一。这可能使得页面更快地加载。不过，要是使用蜗牛到超音速来对比，这个速度还没到达赛车的速度呢！


最后，你可以在 [Google Insights](https://developers.google.com/speed/pagespeed/insights/?url=getfedora.org&tab=mobile) 中查看结果，例如：


![](/data/attachment/album/201810/28/213804cd8asadmrzub1k2b.png)


在移动端部分，这个页面的得分提升了 10 分，但它依然处于“中等”水平。对于桌面端，结果看起来完全不同，从 62/100 分提升至了 91/100 分，等级也达到了“好”的水平。如我们之前所说的，这个测试并不意味着我们的工作就做完了。通过参考这些分数可以让你朝着正确的方向前进。请记住，你正在为用户体验来进行优化，而不是搜索引擎。




---


via: <https://fedoramagazine.org/design-faster-web-pages-part-1-image-compression/>


作者：[Sirko Kemter](https://fedoramagazine.org/author/gnokii/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[StdioA](https://github.com/StdioA) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Lots of web developers want to achieve fast loading web pages. As more page views come from mobile devices, making websites look better on smaller screens using responsive design is just one side of the coin. *Browser Calories* can make the difference in loading times, which satisfies not just the user but search engines that rank on loading speed. This article series covers how to slim down your web pages with tools Fedora offers.


## Preparation

Before you sart to slim down your web pages, you need to identify the core issues. For this, you can use [Browserdiet](https://browserdiet.com/calories/). It’s a browser add-on available for Firefox, Opera and Chrome and other browsers. It analyzes the performance values of the actual open web page, so you know where to start slimming down.

Next you’ll need some pages to work on. The example screenshot shows a test of [getfedora.org](http://getfedora.org). At first it looks very simple and responsive.

![Browser Diet - values of getfedora.org](https://fedoramagazine.org/wp-content/uploads/2018/02/ff-addon-diet.jpg)

Browser Diet – values of getfedora.org

However, BrowserDiet’s page analysis shows there are 1.8MB in files downloaded. Therefore, there’s some work to do!

## Web optimization


There are over 281 KB of JavaScript files, 203 KB more in CSS files, and 1.2 MB in images. Start with the biggest issue — the images. The tool set you need for this is GIMP, ImageMagick, and optipng. You can easily install them using the following command:

sudo dnf install gimp imagemagick optipng

For example, take the [following file](https://getfedora.org/static/images/cinnamon.png) which is 6.4 KB:

First, use the *file* command to get some basic information about this image:

$file cinnamon.pngcinnamon.png: PNG image data, 60 x 60, 8-bit/color RGBA, non-interlaced

The image — which is only in grey and white — is saved in 8-bit/color RGBA mode. That’s not as efficient as it could be.

Start GIMP so you can set a more appropriate color mode. Open *cinnamon.png* in GIMP. Then go to *Image>Mode* and set it to *greyscale*. Export the image as PNG with compression factor 9. All other settings in the export dialog should be the default.

$file cinnamon.pngcinnamon.png: PNG image data, 60 x 60, 8-bit gray+alpha, non-interlaced

The output shows the file’s now in *8bit gray+alpha* mode. The file size has shrunk from 6.4 KB to 2.8 KB. That’s already only 43.75% of the original size. But there’s more you can do!

You can also use the ImageMagick tool *identify* to provide more information about the image.

$identify cinnamon2.pngcinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2831B 0.000u 0:00.000

This tells you the file is 2831 bytes. Jump back into GIMP, and export the file. In the export dialog disable the storing of the time stamp and the alpha channel color values to reduce this a little more. Now the *file* output shows:

$identify cinnamon.pngcinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2798B 0.000u 0:00.000

Next, use *optipng* to losslessly optimize your PNG images. There are other tools that do similar things, including **advdef** (which is part of advancecomp), **pngquant **and** pngcrush.**

Run* optipng* on your file. Note that this will replace your original:

$optipng -o7 cinnamon.png** Processing: cinnamon.png 60x60 pixels, 2x8 bits/pixel, grayscale+alpha Reducing image to 8 bits/pixel, grayscale Input IDAT size = 2720 bytes Input file size = 2812 bytes Trying: zc = 9 zm = 8 zs = 0 f = 0 IDAT size = 1922 zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920 Selecting parameters: zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920 Output IDAT size = 1920 bytes (800 bytes decrease) Output file size = 2012 bytes (800 bytes = 28.45% decrease)

The option *-o7* is the slowest to process, but provides the best end results. You’ve knocked 800 more bytes off the file size, which is now 2012 bytes.

To resize all of the PNGs in a directory, use this command:

$optipng -o7 -dir=<directory>*.png

The option *-dir* lets you give a target directory for the output. If this option is not used, *optipng* would overwrite the original images.

## Choosing the right file format

When it comes to pictures for the usage in the internet, you have the choice between:

JPG-LS and JPG 2000 are not widely used. Only a few digital cameras support these formats, so they can be ignored. aPNG is an animated PNG, and not widely used either.

You could save a few bytes more through changing the compression rate or choosing another file format. The first option you can’t do in GIMP, as it’s already using the highest compression rate. As there are no [alpha channels](https://www.webopedia.com/TERM/A/alpha_channel.html) in the picture, you can choose JPG as file format instead. For now use the default value of 90% quality — you could change it down to 85%, but then alias effects become visible. This saves a few bytes more:

$identify cinnamon.jpgcinnamon.jpg JPEG 60x60 60x60+0+0 8-bit sRGB 2676B 0.000u 0:00.000

Alone this conversion to the right color space and choosing JPG as file format brought down the file size from 23 KB to 12.3 KB, a reduction of nearly 50%.

### PNG vs. JPG: quality and compression rate

So what about the rest of the images? This method would work for all the other pictures, except the Fedora “flavor” logos and the logos for the four foundations. Those are presented on a white background.

One of the main differences between PNG and JPG is that JPG has no alpha channel. Therefore it can’t handle transparency. If you rework these images by using a JPG on a white background, you can reduce the file size from 40.7 KB to 28.3 KB.

Now there are four more images you can rework: the backgrounds. For the grey background, set the mode to greyscale again. With this bigger picture, the savings also is bigger. It shrinks from 216.2 KB to 51.0 KB — it’s now barely 25% of its original size. All in all, you’ve shrunk 481.1 KB down to 191.5 KB — only 39.8% of the starting size.

### Quality vs. Quantity

Another difference between PNG and JPG is the quality. PNG is a lossless compressed raster graphics format. But JPG loses size through compression, and thus affects quality. That doesn’t mean you shouldn’t use JPG, though. But you have to find a balance between file size and quality.

## Achievement

This is the end of Part 1. After following the techniques described above, here are the results:

You brought image size down to 488.9 KB versus 1.2MB at the start. That’s only about a third of the size, just through optimizing with *optipng*. This page can probably be made to load faster still. On the scale from snail to hypersonic, it’s not reached racing car speed yet!

Finally you can check the results in [Google Insights](https://developers.google.com/speed/pagespeed/insights/?url=getfedora.org&tab=mobile), for example:

In the Mobile area the page gathered 10 points on scoring, but is still in the *Medium* sector. It looks totally different for the Desktop, which has gone from 62/100 to 91/100 and went up to *Good*. As mentioned before, this test isn’t the be all and end all. Consider scores such as these to help you go in the right direction. Keep in mind you’re optimizing for the user experience, and not for a search engine.

## Leandro Boari

Good job!

tinypng.com provides excellent compression as well.

## Sirko Kemter

true it does a good job but the difference to optipng and other featured tools, it doesnt work locally. So optipng I can script and automate it in my workflow. With tinypng I cant do that and need an internet connection and cause traffic

## TH301

Excellent start on the series, hope the following will be just as detailed! Maybe dip into Static Site Generators like Hugo and certainly CSS Grid as it’s now well supported and finally makes it possible to make responsive easily maintained superminimalistic code without the help of CSS frameworks, hacks and other nuances that was a necessity of the past.

Ruthlessly spamming some links to get headstarted…

Can I use it? (Yes you can!):

https://caniuse.com/#search=CSS%20Grid%20Layout

Amazingly good talk by Rachel Andrew:

https://www.youtube.com/watch?v=8ti7o-sQuYs

Mozilla docs:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

25 videos by Wes Bos (all free!)

https://cssgrid.io/

Learn CSS Grid by Jonathan Suh:

https://learncssgrid.com/

The specs itself (yeah I know… partly written by Microsoft, but this is actually very good):

https://www.w3.org/TR/css-grid-1/

OK, I need to stop this linkspamming now! 🙂

## Sirko Kemter

no, we will not talk about CSS Grid and site frameworks like Hugo (But if you think thats something to talk about go ahead submit). Actually the title was changed by the editors, so “design” doesnt fit for what we do because we just make a “diet” on what we have, to save “calories” and speed up the loading time.

If you look to the page which we using as example http://getfedora.org. You see, that the changes we did in this part not really make sense as there are better options for the pictures, so we will throw them away and use something what makes more sense… 😉

## TH301

Maybe not SSG, but I still think CSS Grid makes a lot of sense for taking getfedora.org on a diet and reducing its CSS calories, which is the highest % load in your screenshot. Getfedora.org are currently using the CSS framework Bootstrap. CSS Grid is kind of like a framework, but built directly into the browsers itself so you could get rid of Bootstrap altogether and more. Looking at the html source there’s a lot of div’s and bootstrap-classes that would no longer be needed as well and thereby reducing the overall load even further. It’s your series and I’m sure I will enjoy the read however it expands, but I do hope you will reconsider here.

## Sirko Kemter

I am sure the web team takes every help they can get

## TH301

I have to admit that when writing my first comment I thought the series was just just using getfedora.org to give some general advises and not actually be applied on getfedora.org. Applying grid would require a lot more work and testing so I totally understand why grid would be out of the scope for this series. That’s cool.

Moving to grid however is still something I think would be beneficial for the future, so if I want to get my hands dirty (no promises), then were…

1. Do I start a start a proper discussion with the web team?

2. Do I submit patches against the website? Maybe there’s are a GitLab/Hub repo for this?

I’m not familiar with how Fedora is organized so any direction would be helpful.

PS: Also out of scope for this series, but when first speaking to a member I would strongly advice to get rid of all

inlineJavaScript and CSS so that CSP can be applied: https://infosec.mozilla.org/guidelines/web_security#content-security-policyAnd fedoramagazine.org is loading external JavaScript with no integrity check (SRI), that’s very easy and takes no time to apply: https://infosec.mozilla.org/guidelines/web_security#subresource-integrity

Thanks for the improvements you make and all the best wishes for this series my friend. 🙂

## Clément Verna

Hi you can get in contact with the website team here (https://pagure.io/fedora-websites), help and suggestions are always welcome 🙂

## Sirko Kemter

Pagure would be if you want to opening a conversation just via filing a bug. For all other we have this wonderful overview page under http://join.fedoraproject.org , where you find the ways how to join the different teams. For websites you have then a link to https://fedoraproject.org/wiki/Websites where you find, how to communicate with the team and what steps to do to become part of them.

## Martin

Good to see this series!

## Manuel Cabrera Caballero

Great, I’ll start to apply it.

## Linux Creative

My Tips for a ‘Site-Diet’ use “Save For Web” in GIMP for Graphics and ‘Ditch Bloated CSS/JavaScript Frameworks’ use custom CSS & Vanilla JS, modern browsers desktop/mobile has no problem with them. Also Dump all the Social Media and other Third-Party Junk Code slowing down sites. MSIE is Dead – It’s time to ‘Code Normal Again’ 8)

## Sirko Kemter

of course a binary plugin for GIMP that for his newer versions not exist anymore and still you had to know what you do

## D

The advise here seems very outdated. Guetzli (near-lossless) and Zopfli (lossless) yields much better compression ratios for JPEG and PNG than traditional compactor tools. New image file formats like WebP yields even smaller files still and works with all major browsers (sans Firefox).

## W

Thank you for your guetzli tip !

Optimized content downloaded from pagespeed insights provided me from 100kb 33kb image, but guetzli at 84% created 19kb image.

Although my site has 100/100 of pagespeed insights ( tips here https://dev.daanvandenbergh.com/wordpress/quick-guide-pagespeed-insights-pingdom/ )

## Sirko Kemter

to sad but guetzli isnt packaged for Fedora yet. WebP as long FF supports it, it would be crazy to use it. But the next version shall support it lets see.

## Rene Reichenbach

Its crucial to say that it mainly depends on the color count what format is the one to head for.

rule of thumbs is:

icons or graphics (low color count) png

pictures or fotos (high color count) jpg

and you could explain a bit more about vector graphics (svg)

Besides this its a nice topic and i am looking forward to the next articles.

## Sirko Kemter

a) what has the “color count” to do with the format?

b) its a series, so I would wait for SVG

## Marcio

Muito bom, o artigo é foi muito útil para melhor o desempenho do meu site, entretanto oi maior gargalo está por conta do JavaScript e o CSS!

## Sirko Kemter

as you comment to me in your mother tongue, I will answer in mine:

In der Ueberschrift steht, Part I was am Ende meint, es wird weitere Teile geben auch solche, die sich mit der Problematik von zu viel JS und CSS auseinandersetzen

## Kitty

Any ideas on how to compress an animated JPEG?

## Sirko Kemter

jpeg is already compressed 😉 You might improve the compression rate. But the question is, how is it animated 😉

## Laurie

Hi there, hearing a lot of buzz about the new animated JPEG format, any way to double compress these?