Last active
March 27, 2020 18:40
-
-
Save kenzo0107/553de689851f5f7149029c7e444c23ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 【TRY】画像変換コマンドを作ろう | |
package main | |
import ( | |
"fmt" | |
"image/jpeg" | |
"image/png" | |
"log" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
path := "hoge.jpg" | |
basename := getBasename(path) | |
println(basename) | |
if err := jpg2png(path); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func getBasename(path string) string { | |
lenBasename := len(path) - len(filepath.Ext(path)) | |
return filepath.Base(path[:lenBasename]) | |
} | |
func jpg2png(path string) error { | |
f, err := os.Open(path) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
jpgImg, err := jpeg.Decode(f) | |
if err != nil { | |
return err | |
} | |
basename := getBasename(path) | |
pngImgName := fmt.Sprintf("%s.png", basename) | |
d, err := os.Create(pngImgName) | |
if err != nil { | |
return err | |
} | |
defer d.Close() | |
err = png.Encode(d, jpgImg) | |
if err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment