diff --git a/kadai1/tsubasaxzzz/main.go b/kadai1/tsubasaxzzz/main.go new file mode 100644 index 0000000..44ac1dc --- /dev/null +++ b/kadai1/tsubasaxzzz/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "flag" + "fmt" + "myimage" + "os" + "path/filepath" + "strings" +) + +var ( + dir = flag.String("dir", ".", "Target directory") + fromExt = flag.String("from-ext", "", "From extention") + toExt = flag.String("to-ext", "", "To extention") +) + +func main() { + flag.Parse() + startPath := filepath.Join(*dir) + + fmt.Printf("Convert image file start.: target=[%s], from-extension=[%s], to-extension=[%s]\n", *dir, *fromExt, *toExt) + + err := filepath.Walk(startPath, + func(path string, info os.FileInfo, err error) error { + // オプションで指定された拡張子のファイルの場合のみ + if strings.Replace(filepath.Ext(path), ".", "", 1) == *fromExt { + convfunc, err := myimage.GetConvertFunc(*fromExt, *toExt) + if err == nil { + fmt.Printf("Convert image file: filepath=[%s]\n", path) + convfunc(path) + } else { + fmt.Printf("Skip convert image file: filepath=[%s], reason=[%s]\n", path, err) + } + } + return err + }) + if err != nil { + fmt.Printf("Error occured: error=[%s]\n", err) + } + fmt.Printf("Convert image file end.\n") +} diff --git a/kadai1/tsubasaxzzz/src/myimage/myimage.go b/kadai1/tsubasaxzzz/src/myimage/myimage.go new file mode 100644 index 0000000..b1512d9 --- /dev/null +++ b/kadai1/tsubasaxzzz/src/myimage/myimage.go @@ -0,0 +1,78 @@ +package myimage + +import ( + "errors" + "image/jpeg" + "image/png" + "os" + "path/filepath" +) + +// 拡張子と対応する変換関数のマッピング +var format = map[string]map[string]ConvertFunc{ + "jpg": { + "png": jpg2png, + }, + "jpeg": { + "png": jpg2png, + }, + "png": { + "jpg": png2jpg, + }, +} + +// ConvertFunc is express of convert functions. +type ConvertFunc func(path string) error + +// 拡張子削除関数 +func getFilePathWithoutExt(path string) string { + return path[:len(path)-len(filepath.Ext(path))] +} + +// ---------------------------- +// 変換関数 +//----------------------------- +// JPEG -> PNG +func jpg2png(path string) error { + inFile, err := os.Open(path) + if err != nil { + return err + } + img, err := jpeg.Decode(inFile) + if err != nil { + return err + } + + outFile, err := os.Create(getFilePathWithoutExt(path) + ".png") + if err != nil { + return err + } + + return png.Encode(outFile, img) +} + +// PNG -> JPG +func png2jpg(path string) error { + inFile, err := os.Open(path) + if err != nil { + return err + } + img, err := png.Decode(inFile) + if err != nil { + return err + } + outFile, err := os.Create(getFilePathWithoutExt(path) + ".jpg") + if err != nil { + return err + } + + return jpeg.Encode(outFile, img, &jpeg.Options{Quality: 100}) +} + +// GetConvertFunc is in order to get ConvertFunc by from and to extension. +func GetConvertFunc(fromExt string, toExt string) (convfunc ConvertFunc, err error) { + if val, ok := format[fromExt][toExt]; ok { + return val, nil + } + return nil, errors.New("Convert function not found") +}