refactor(worker): replace direct command execution with utility function for image compression and update test output for accuracy

This commit is contained in:
keven1024
2026-02-25 15:35:28 +08:00
parent 155c697e53
commit e9d0848f87
3 changed files with 22 additions and 9 deletions

View File

@@ -2,7 +2,6 @@ package services
import (
"errors"
"os/exec"
"worker/internal/utils"
)
@@ -10,9 +9,7 @@ func CompressImage(filePath string, mimeType string) (string, error) {
compressedPath := filePath + "_compressed"
switch mimeType {
case "image/png":
args := []string{"--output", compressedPath, filePath}
cmd := exec.Command("pngquant", args...)
_, err := cmd.CombinedOutput()
_, err := utils.RunCommand("pngquant", "--output", compressedPath, filePath)
if err != nil {
return "", err
}
@@ -21,9 +18,7 @@ func CompressImage(filePath string, mimeType string) (string, error) {
if err != nil {
return "", err
}
args := []string{"-m", "90", "--strip-all", compressedPath}
cmd := exec.Command("jpegoptim", args...)
_, err = cmd.CombinedOutput()
_, err = utils.RunCommand("jpegoptim", "-m", "80", "--strip-all", compressedPath)
if err != nil {
return "", err
}

View File

@@ -0,0 +1,18 @@
package utils
import (
"context"
"os/exec"
"time"
)
func RunCommand(bin string, args ...string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, bin, args...)
bytes, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
return bytes, nil
}

View File

@@ -36,7 +36,7 @@ func TestCompressPNGHappyPath(t *testing.T) {
t.Fatal(err)
}
assert.NotEqual(t, origInfo.Size(), compInfo.Size())
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(origInfo.Size())/float64(compInfo.Size())*100)
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(compInfo.Size())/float64(origInfo.Size())*100)
}
func TestCompressJPEGHappyPath(t *testing.T) {
@@ -62,5 +62,5 @@ func TestCompressJPEGHappyPath(t *testing.T) {
t.Fatal(err)
}
assert.NotEqual(t, origInfo.Size(), compInfo.Size())
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(origInfo.Size())/float64(compInfo.Size())*100)
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(compInfo.Size())/float64(origInfo.Size())*100)
}