3

利用GitHub Actions自动对仓库内图片进行无损压缩

 1 year ago
source link: https://wiki.eryajf.net/pages/dbee9e/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

利用GitHub Actions自动对仓库内图片进行无损压缩原创

我维护的 awesome-github-profile-readme-chinese (opens new window) 项目旨在收集汇总中文区优秀的个人主页,每个人的主页将会通过截图的方式存放在 exampls 目录下,有时候有的朋友主页内容很多,这样整体截图下来就非常大。

本文就介绍一个有意思的小动作,它的主要功能是可以自动扫描仓库内的图片,然后对其进行几乎无损的压缩,让整个仓库的体积保持在一个相对低的水平。

所用Actions:image-actions (opens new window)

使用配置其实非常简单,基本上阅读完官方介绍文档就可以上手使用了,这里说一两个需要注意的地方。

首先添加Actions配置文件,e.g. .github/workflows/images.yml

name: 压缩图片
on:
  push:
    branches:
      - main
    paths:
      - 'examples/**'
  pull_request:
    paths:
      - 'examples/**'
  workflow_dispatch:
jobs:
  build:
    name: calibreapp/image-actions
    runs-on: ubuntu-latest
    # Only run on main repo on and PRs that match the main repo.
    if: |
      github.repository == 'example/example_repo' &&
      (github.event_name != 'pull_request' ||
       github.event.pull_request.head.repo.full_name == github.repository)
    steps:
      - name: Checkout Branch
        uses: actions/checkout@v2
      - name: Compress Images
        id: calibre
        uses: calibreapp/image-actions@main
        with:
          githubToken: ${{ secrets.GITHUB_TOKEN }}
          # For non-Pull Requests, run in compressOnly mode and we'll PR after.
          compressOnly: true
          jpegQuality: '60'
          jpegProgressive: false
          pngQuality: '60'
          webpQuality: '60'
      - name: Create Pull Request
        # If it's not a Pull Request then commit any changes as a new PR.
        if: |
          github.event_name != 'pull_request' &&
          steps.calibre.outputs.markdown != ''
        uses: peter-evans/create-pull-request@v3
        with:
          title: Auto Compress Images
          branch-suffix: timestamp
          commit-message: Compress Images
          body: ${{ steps.calibre.outputs.markdown }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

需要注意,压缩图片的动作,在运行之后,会自动将图片二次commit上来,这就要求该动作具有对应commit的权限才行,通常我们配置的token没有其他开发者fork之后的仓库的权限,于是这里并不能直接处理其他人PR过来的内容中的图片。

官方给出的建议是:

  • 要么其他开发者通过在主仓库check一个分支,然后在主仓库进行分支的PR。但这种方式其实并非是GitHub中协作的主流场景,多用在开发者个人维护的流程。
  • 要么就是先处理其他人通过fork的方式提交上来的PR,当PR被同意之后,会自动进行扫描检查,然后该动作完成图片压缩之后,再自动创建一个新的PR,来完成图片的压缩。

还需要注意的一点是:其中的 secrets.GITHUB_TOKEN是操作当前仓库使用的,不需要进行更改,如果改了,反而会报错。

效果如下:

1fa538021f1f5631.png

这个动作会自动将图片处理好,然后提交到当次PR上,我们可以点开 View diff查看前后的区别:

92fefdc809ad227d.png

目前这个效果据我个人放大前后两张照片来看,在体积缩小了80%的情况下,清晰度几乎是一致的,还是非常给力的一个动作,适合那些存放图片比较多的仓库。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK