Skip to content

Commit d959ba1

Browse files
committed
加强压缩效果
1 parent d1b33db commit d959ba1

3 files changed

Lines changed: 26 additions & 6 deletions

File tree

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1580,8 +1580,8 @@ docker buildx build \
15801580
--build-arg VERSION=v2.4.1 \
15811581
--build-arg INSTALL_FFMPEG=0 \
15821582
--build-arg USE_UPX=1 \
1583-
-t noise233/echo-noise:v2.4.1-slim \
1584-
-t noise233/echo-noise:slim \
1583+
-t noise233/echo-noise:v2.4.1-amd64 \
1584+
-t noise233/echo-noise:last-amd64 \
15851585
--push --no-cache .
15861586
```
15871587

pkg/compress.go

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,11 @@ func CompressImageWithFFmpeg(inputData []byte, ext string) ([]byte, error) {
118118
return nil, err
119119
}
120120

121+
// 如果压缩后体积没有变小(甚至更大),直接返回原始数据,避免“压缩几乎无效果”的体验
122+
if len(compressedData) >= len(inputData) {
123+
return inputData, nil
124+
}
125+
121126
return compressedData, nil
122127
}
123128

@@ -132,12 +137,17 @@ func CompressVideoWithFFmpeg(inputPath string) (string, error) {
132137
tmpOutput := filepath.Join(os.TempDir(), "compressed-"+uuid.New().String()+outputExt)
133138

134139
// 构建 FFmpeg 命令
135-
// -crf 28: 压缩质量 (18-28 是合理范围)
136-
// -preset fast: 编码速度
140+
// -vf scale: 对超大视频进行降分辨率以获得更明显的压缩收益
141+
// -crf 30: 更激进的压缩(文件更小)
142+
// -preset medium: 比 fast 更小,但 CPU 消耗更高
143+
// -b:a 96k: 音频更小
144+
// -pix_fmt yuv420p: 兼容性更好
137145
// -movflags +faststart: 优化 Web 播放(元数据移到文件头)
138146
cmd := exec.Command(ffmpegBinaryPath, "-y", "-i", inputPath,
139-
"-vcodec", "libx264", "-crf", "28", "-preset", "fast",
140-
"-acodec", "aac", "-b:a", "128k",
147+
"-vf", "scale='min(1280,iw)':-2",
148+
"-vcodec", "libx264", "-crf", "30", "-preset", "medium",
149+
"-pix_fmt", "yuv420p",
150+
"-acodec", "aac", "-b:a", "96k",
141151
"-movflags", "+faststart",
142152
tmpOutput)
143153

@@ -146,5 +156,15 @@ func CompressVideoWithFFmpeg(inputPath string) (string, error) {
146156
return "", fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
147157
}
148158

159+
// 如果压缩后体积没有变小(甚至更大),放弃压缩结果
160+
inStat, inErr := os.Stat(inputPath)
161+
outStat, outErr := os.Stat(tmpOutput)
162+
if inErr == nil && outErr == nil {
163+
if outStat.Size() >= inStat.Size() {
164+
os.Remove(tmpOutput)
165+
return "", nil
166+
}
167+
}
168+
149169
return tmpOutput, nil
150170
}

server

85.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)