圖片無損壓縮下的演算法比較

Hacker News 上看到「What’s the best lossless image format? Comparing PNG, WebP, AVIF, and JPEG XL」這篇,在講圖片的無損壓縮演算法。在 Hacker News 上的討論也可以看看:「What’s the best lossless image format? (siipo.la)」。

文章有點舊 (2021 年七月),但應該還行... 另外作者看起來是以 service bandwidth 考量為主,在這種情境下,自然圖片一般都會以非無損的方式提供 (像是 JPEG),而人造圖片則是以無損的方式提供 (像是 PNG),所以在這邊討論無損的時候會以人造圖片的 dataset 來挑選,於是作者是跑去 Dribbble 上翻圖片當 dataset:

What I ended up with was downloading a set of images from Dribbble, a portfolio site for designers.

最後的結果就是:

考慮到目前各家瀏覽器的支援性,可以看到 Lossless WebP 其實是個很好的選擇,檔案算蠻小的,而且 Apple ecosystem 的支援性也已經出來了:

如果不用考慮到瀏覽器的話,JPEG XL 也可以考慮,不過本來宣稱 royalty-free 的部份蒙上了陰影:「Alarm raised after Microsoft wins data-encoding patent」,用的人反而要注意到 patent 問題...

Cloudflare Images

Cloudflare Images 開放付費使用了:「Cloudflare Images Now Available to Everyone」。

檔案傳到 Cloudflare 上面,然後另外收處理費用:

You pay $5/month for every 100,000 stored images and $1 per 100,000 delivered images. There are no additional resizing, compute or egress costs.

檔案大小的限制是 10MB,所以 $5/month 的 storage 最多可以提供 1TB 的空間,$0.005/GB 算是很漂亮的數字,如果是小圖的話就會比較虧一些?看起來丟大圖會開心一點...

Cloudflare Images offers multiple ways to upload your images. We accept all the common file formats including JPEG, GIF and WEBP. Each image uploaded to Images can be up to 10 MB.

然後支援的檔案格式有常見的 GIFJPEGPNG 以及 WebP

When a client requests an image, Cloudflare Images will pick the optimal format between WebP, PNG, JPEG and GIF.

另外有計畫要支援 AVIF

We’re just getting started with Cloudflare Images. Here are some of the features we plan to support soon:

AVIF support for even smaller file sizes and faster load times.

沒提到 durability,不知道會有多少...

重寫 Ptt 上的 Imgur Userscript 解決圖片出不來的問題

前幾個禮拜 Imgur 決定擋掉 Ptt 的網頁版,所以 Ptt 網頁版上會發現 Imgur 的圖都不見了:「[問題] 突然imgur的貼圖無法顯示」。

這是因為 Imgur 用 Referer 擋了 Ptt 的關係,後來 Ptt 官方在 8/15 後有針對 https://i.gslin.com/imgur/ 的圖片改用 https://cache.ptt.cc/ 過一層,不過 https://imgur.com/ 的就沒圖了。

這邊可以參考 Certificate Transparency 的「crt.sh | cache.ptt.cc」記錄,以及台大對於 Ptt 的流量的記錄 (出自「PTT 流量分析」這邊):

除了 Ptt 官方的解法外,另外可以自己寫 userscript,用 Referrer-Policy 繞過 (需要比較新版的瀏覽器,不過目前的瀏覽氣應該都夠新),看了一下本來的 ptt-imgur-cleaner-gm,發現要整個打掉改寫,索性就開一個新的專案變成 imgur-links-rewriting-on-ptt

這個版本的特色:

  • 加上對 https://imgur.com/a/ (album) 的支援,可以顯示第一張圖。
  • WebP 的版本,下載速度應該會快一些。
  • 偏好都是用大圖 (原始大小的圖片)。
  • 把本來走 https://cache.ptt.cc/ 的版本換回直接走 https://i.gslin.com/imgur/,就不用透過 TANet 或是台大的出國頻寬了。

程式碼不長 (參考「imgur-links-rewriting-on-ptt.user.js」這邊),主要是練手... 沒事就寫一下 userscript 可以維持對於 JavaScript 的基本熟悉度。

AVIF 與 WebP 的懶人包設定?

看到「AVIF and WebP encoding quality settings」這包,看起來是 AVIFWebP 的懶人包設定。

一分鐘版的懶人包設定是基於一般 JPEG 的 quality 設定為 60 時的畫質,與 AVIF 的 50,WebP 的 65 差不多:

If you usually encode JPEGs with quality setting 60, then encode AVIF with quality setting 50 and WebP with quality setting 65. You should expect your AVIF files to be on average 36% smaller and your WebP images 15% smaller than the equivalent JPEG image.

後面給的複雜一點,包括了 JPEG quality 在 50/60/70/80 的情況。

作者用的是 DSSim 判斷圖片壓縮後的品質,看了維基百科裡面的說明,讓我想到 2016 年時 Netflix 公開的 VMAF,針對影片的品質分析:「Netflix 評估影片品質的方法」。

不過沒碰太多這塊的東西,不確定 DDSim 目前是否有被認可... 留下來當作參考。

用 picture + source + img 替代本來的 JavaScript 替換

目前我在 blog 上使用 Imgur 的圖檔主要是用 WebP 格式,然後針對不支援 WebP 的瀏覽器 (主要就是蘋果家的 Safari) 是用 JavaScript 換回 JPEG 格式...

昨天早上看到「AVIF has landed」這篇,提醒我有 <picture> 這個原生支援的方式可以用,翻了一下 Can I Use 上面的支援程度,看起來除了 IE11 以外幾乎都支援了 (參考「Picture element」),而且 IE11 應該也會因為語法的關係走到正確的 JPEG fallback,大概是這樣:

<picture>
    <source type="image/webp" srcset="https://i.gslin.com/imgur/xxxxxx.webp" />
    <img src="https://i.gslin.com/imgur/xxxxxx.jpg" alt="" />
</picture>

換完後來觀察看看...

Chrome 85 支援 AVIF

看到「How to Use AVIF: The New Next-Gen Image Compression Format」這篇在推銷用 AVIF 取代 JPEGWebP

首先是跑去 Can I Use 翻,發現 Google Chrome 85 之後支援了,另外在「Issue 960620: Support AVIF」這邊可以看到對應的 ticket,以及「AVIF Image Decode」這邊有狀態:

Enabled by default (tracking bug) in:
Chrome for desktop release 85

現在的 stabel channel 是 84,所以是下個 release 就會有了。以 Google Chrome 的市占率來說,推出來等於是支援度直接過半... 這點也的確有人批評,不過又是另外一個話題了。

對於不支援 AVIF 的瀏覽器,也有對應的 polyfill 可以上 (用 javascript 去補功能),不過因為是透過 AV1 codec,能夠向下支援的版本還是不多,除非連 AV1 都透過 polyfill 支援:「AVIF (AV1 Still Image File Format) polyfill for the browser」。

另外在寫「WebP 的檔案大小未必比 JPEG 小...」這篇時有提過 AVIF 其實也不是完美的,畢竟是從 video codec 演化來的演算法,對於演算法判斷不重要的部位會掉比較多細節...

WebP 的檔案大小未必比 JPEG 小...

在「Is WebP really better than JPEG?」這邊發現在差不多的條件需求下,WebP 壓出來的檔案大小未必會比 JPEG 小。

先講結論:提供服務的人可以先確認自家的 JPEG 壓縮是不是有先用 MozJPEG (壓縮率更好),然後再考慮要不要支援 WebP。

Google 在推 WebP 這個格式的時候,宣稱失真壓縮的部份可以比 JPEG 小 25%~34%:(出自「A new image format for the Web」)

WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index.

但作者發現 Google 之所以可以達到 25%~34% 這個數字,是因為比較的對象是 Independent JPEG Group 所釋出的 cjpeg,而如果拿 MozJPEG 相比的話應該得不到這個結果,另外也把 AV1 的 AVIF 拉進來一起測試了:

I think Google’s result of 25-34% smaller files is mostly caused by the fact that they compared their WebP encoder to the JPEG reference implementation, Independent JPEG Group’s cjpeg, not Mozilla’s improved MozJPEG encoder. I decided to run some tests to see how cjpeg, MozJPEG and WebP compare. I also tested the new AVIF format, based on the open AV1 video codec. AVIF support is already in Firefox behind a flag and should be coming soon to Chrome if this ticket is to be believed.

這邊作者測試用的圖集是 Kodak Lossless True Color Image Suite,測試的結果發現 WebP 的確比 libjpeg (cjpeg) 好一些,但沒有像 Google 講的那麼多 (這邊就不知道是不是現在的 libjpeg 又有改善),而 WebP 與 MozJPEG 相比的話就沒有明顯優勢了:

WebP seems to have about 10% better compression compared to libjpeg in most cases, except with 1500px images where the compression is about equal.

However, when compared to MozJPEG, WebP only performs better with small 500px images. With other image sizes the compression is equal or worse.

I think MozJPEG is the clear winner here with consistently about 10% better compression than libjpeg.

另外也提到了 AVIF 的壓縮率很好,不過要注意演算法會把非重點部位的細節吃掉:

I think AVIF is a really exciting development and compared to WebP it seems like a true next-generation codec with about 30% better compression ratio compared to libjpeg. Only concern I have is the excessive blurring of low detail areas. It remains to be seen if this can be improved when more advanced tooling becomes available.

對網頁的應用來說,WebP 另外一個痛點是在 Safari 上的支援度,在 caniuse.com 的「WebP image format」這邊可以看到目前各瀏覽器都支援了,就剩下 Safari 還不支援,所以目前在 iOS 上得降回 JPEG:

不過這點之後也改變了,在 iOS 14 beta 裡的 Safari 可以看到支援 WebP 了:「Safari 14 Beta Release Notes」。

Media
New Features
Added WebP image support.

所以這個狀況變得有點微妙了...

把 Blog 上的 PNG 圖片換成 WebP 格式

WebP 格式的大小比起 JPEG 或是 PNG 都小不少,支援度也都還行,但 Safari 不支援是個大問題,因為在行動裝置裡面 iOS 還是大宗...

目前想到的方法是只對 Imgur 的圖片使用 WebP (.webp),當遇到不支援的 WebP 的平台時透過 JavaScript 改用 PNG (.png)。

這邊有判斷有沒有支援 WebP 的程式碼出自「Detect WEBP Support with JavaScript」,用 createImageBitmap() 建看看有沒有成功:

(() => {
  let supportsWebP = async () => {
    if (!self.createImageBitmap) return false;
    const webpData = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
    const blob = await fetch(webpData).then(r => r.blob());
    return createImageBitmap(blob).then(() => true, () => false);
  };

  (async () => {
    if (!await supportsWebP()) {
      document.addEventListener('DOMContentLoaded', () => {
        for (let el of document.getElementsByTagName('img')) {
          let src = el.getAttribute('src');
          if (src.match(/\.webp/)) {
            el.setAttribute('src', src.replace(/\.webp/, '.png'));
          }
        }
      });
    }
  })();
})();

這邊比較有趣的是網路上的文件 (MDNCanIuse) 都說 Safari 不支援 createImageBitmap(),但實際上好像沒問題 :o

然後再用 WordPress 的延伸套件「Search Regex」把所有文章理出現 /https:\/\/i\.imgur\.com/(\w+)\.png/ 的字串換成 https://i.gslin.com/imgur/$1.webp,接下來就可以拿 Safari 測試了,這樣有點 hack 但看起來還行...

使用 PNG 對圖片失真壓縮...

PNG 是無失真影像壓縮格式,但我們仍然可以修改 pixel (失真) 讓 PNG 壓縮率更好。今天在「PNG can be a lossy format」看到的 Mac OS X 應用程式就是這個用途。

雖然是應用程式,但作者還是有說明 algorithm 是哪些,分別是從哪裡來。其中兩個是:

文章最後,作者對 GIF 很感冒... XD

GIF has antiquated compression and it's a complete waste of bandwidth. Even lossy GIF is worse than lossless optimized PNG.

另外,JPEG/WebP 還是比較小,不過 JPEG 有很多格式,瀏覽器與作業系統的支援度還是很大的阻礙:

Whether lossy PNG gives better results than JPEG depends on the image. JPEG often gives smaller files, except when image has sharp edges (e.g. text) or any transparency (which JPEG does not support at all).

Optimized lossy PNG is still a bit larger than lossy JPEG-XR/WebP/JPEG-2K, but unlike these formats it's supported by all browsers and operating systems without any fuss or hacks.

最後發現 lossypng 是 Go 寫的,程式碼也不長,看起來頗好玩的... (也許包成 ports?)

Google 發佈 WebP,號稱比 JPEG 更好的圖片壓縮格式...

Google 剛剛發表了 WebP,一個從 VP8 擷取出來的圖片壓縮格式:「WebP, a new image format for the Web」。

以 Google 的說法,從網路上隨機抽一百萬張圖片測試,原先使用 JPEG、PNG、GIF 壓縮的圖片,改用 WebP 後可以節省 39% 的空間。但這邊沒有提到測試的細節,像是壓縮後的品質,以及這一百萬張圖片是如何取樣...

雖然在官方網站上有「Sample image files in JPEG and WebP」可以看,但比較奇怪的是,Lenna 居然沒有列出來,這幾乎是圖片壓縮的必測項目?

目前的 WebP 只是先從 VP8 抽出來而已,還沒有加到 Google Chrome 裡,不過就網頁上的說明,已經在計畫了。