@@ -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}
0 commit comments