mirror of
https://github.com/keven1024/015.git
synced 2026-06-09 22:04:34 +00:00
refactor(worker): replace direct command execution with utility function for image compression and update test output for accuracy
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
18
worker/internal/utils/cmd.go
Normal file
18
worker/internal/utils/cmd.go
Normal 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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user