快速壓縮圖片方法(小白篇)


0 適用場景

批量上傳圖片到雲服務器(例如七牛雲),但不需要用這么高清的圖片。

例如發文章在得物,小紅書等平台時。

1 前提

2 腳本

2.1 核心代碼

#批量把當前目錄的jpg圖片 分辨率下降至25%,質量下降一半成像
#假定文件名:batchCompressImagesIncludeSubFiles5050.sh
magick *.jpg -resize 50% -quality 50 op_%03d.jpg

2.2 批量處理

說明:批量處理指定文件夾及子文件夾所有圖片

2.2.1 帶參數

指定目錄及分辨率及質量三個參數

文件名:batchCompressImagesIncludeSubFilesWithParams.sh

#!/bin/bash
read_dir(){
    echo 'start walk through dir of'$1
    suffixJpg='.jpg'
    suffixJpeg='.jpeg'
    suffixPng='.png'
    for file in `ls -a $1`
    do
        if [ -d $1"/"$file ]
        then
            if [[ $file != '.' && $file != '..' ]]
            then
                read_dir $1"/"$file
            fi
        else
            echo $1"/"$file
            if [[ ${file:0-4:4} == ${suffixJpg} ||  ${file:0-5:5} == ${suffixJpeg} ]]
            then
                magick  $1"/"$file -resize $2% -quality $3%  $1"/"op_$file
            fi
            if [[ ${file:0-4:4} == ${suffixPng} ]]
            then
                magick  $1"/"$file -resize $2% -quality $3%  $1"/"op_$file.jpg
            fi
        fi
    done
    echo 'walk complete for dir of'$1
}
read_dir $1 $2 $3

2.2.1 簡化版

指定目錄

文件名:batchCompressImagesIncludeSubFiles5050.sh

#!/bin/bash
read_dir(){
    suffixJpg='.jpg'
    suffixJpeg='.jpeg'
    suffixPng='.png'
    for file in `ls -a $1`
    do
        if [ -d $1"/"$file ]
        then
            if [[ $file != '.' && $file != '..' ]]
            then
                read_dir $1"/"$file
            fi
        else
            echo $1"/"$file
            if [[ ${file:0-4:4} == ${suffixJpg} ||  ${file:0-5:5} == ${suffixJpeg} ]]
            then
                magick  $1"/"$file -resize 50% -quality 50  $1"/"op_$file
            fi
            if [[ ${file:0-4:4} == ${suffixPng} ]]
            then
                magick  $1"/"$file -resize 50% -quality 50  $1"/"op_$file.jpg
            fi
        fi
    done
}
read_dir $1

文件名:runCompressSubFiles.sh

#.代表當前所在目錄
batchCompressImagesIncludeSubFiles5050.sh .

3 使用及效果

3.1 使用樣例

  1. 打開git bash

  2. 輸入runCompressSubFiles onedir

  3. 回車

3.2 效果

壓縮后的圖片和原圖,眼睛上看差別幾乎沒有(由於現在手機拍照像素高,拍出來5M起)。

 

文件名 原圖大小 壓縮后大小 壓縮率
four.jpg 9282 KB 307 KB 3.31%
one.jpg 6433 KB 364 KB 5.66%
two.png 24846 KB 739 KB 2.97%

 

four.jpg

 

 

op_four.jpg

 

 

 4 參考

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM