1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| package main
import ( "bytes" "fmt" "github.com/chai2010/webp" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "os" "path/filepath" "strings" )
func main() { if len(os.Args) < 2 { fmt.Println("Usage: png2webp <input.png>|<dir> [quality] [-lossless] [-dir_walker]") return } quality := 80 lossless := false dirWalker := false for _, arg := range os.Args[2:] { if strings.HasPrefix(arg, "-") { if strings.HasPrefix(arg, "-lossless") { lossless = true } if strings.HasPrefix(arg, "-dir_walker") { dirWalker = true } } else { _, _ = fmt.Sscanf(arg, "%d", &quality) } } if dirWalker { err := filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !strings.HasSuffix(strings.ToLower(path), ".png") && !strings.HasSuffix(strings.ToLower(path), ".jpg") && !strings.HasSuffix(strings.ToLower(path), ".jpeg") && !strings.HasSuffix(strings.ToLower(path), ".gif") { return nil } png2webp(path, lossless, quality) return nil }) if err != nil { fmt.Printf("执行过程中出错:%s\n", err) return } } else { png2webp(os.Args[1], lossless, quality) } }
func png2webp(path string, lossless bool, quality int) { outputFileName := strings.TrimSuffix(path, filepath.Ext(path)) + ".webp" inputFile, err := os.Open(path) if err != nil { fmt.Printf("无法打开输入文件:%s\n", err) return } defer inputFile.Close() pngImage, f, err := image.Decode(inputFile) fmt.Printf("读取图片:%s\n", f) if err != nil { fmt.Printf("无法解码 PNG 图片:%s\n", err) return } var webpBuffer bytes.Buffer if lossless { err = webp.Encode(&webpBuffer, pngImage, &webp.Options{Lossless: true}) } else { err = webp.Encode(&webpBuffer, pngImage, &webp.Options{Quality: float32(quality)}) } if err != nil { fmt.Printf("无法编码为 WebP 格式:%s\n", err) return } err = os.WriteFile(outputFileName, webpBuffer.Bytes(), 0666) if err != nil { fmt.Printf("无法写入输出文件:%s\n", err) return } fmt.Println("图片转换成功!") }
|