【Golang】png画像に枠線をつける
Go言語でpng画像にimageパッケージを使用して枠線をつけてみます。
下記のpng画像に赤枠をつけてみます。
画像に枠線をつけるコード
下記のコードはpng画像を読み込み、赤枠線をつけて別画像として保存するコードです。
1package main
2
3import (
4 "image"
5 "image/color"
6 "image/draw"
7 "image/png"
8 "os"
9)
10
11func main() {
12 picPath := "shape.png"
13 savePath := "shape_frame.png"
14 err := addPictureFrame(picPath, savePath)
15 if err != nil {
16 panic(err)
17 }
18}
19
20func addPictureFrame(picPath, savePath string) error {
21 file, err := os.Open(picPath)
22 if err != nil {
23 return err
24 }
25 defer file.Close()
26
27 img, _, err := image.Decode(file)
28 if err != nil {
29 return err
30 }
31
32 bounds := img.Bounds()
33 // image.Imageのままだと編集できないので、image.RGBAに変換する
34 m := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
35 draw.Draw(m, m.Bounds(), img, bounds.Min, draw.Src)
36
37 // 赤色で枠線を描画する
38 c := color.RGBA{255, 0, 0, 255}
39 drawBounds(m, c)
40
41 output, err := os.Create(savePath)
42 if err != nil {
43 return err
44 }
45 defer output.Close()
46
47 png.Encode(output, m)
48 return nil
49}
50
51func drawBounds(img *image.RGBA, c color.Color) {
52 // 枠線の幅
53 paintRange := 10
54
55 for x := 0; x < img.Rect.Max.X; x++ {
56 for offset := 0; offset < paintRange; offset++ {
57 img.Set(x, 0+offset, c) // 画像の上側
58 img.Set(x, img.Rect.Max.Y-1-offset, c) // 画像の下側
59 }
60 }
61
62 for y := 0; y < img.Rect.Max.Y; y++ {
63 for offset := 0; offset < paintRange; offset++ {
64 img.Set(0+offset, y, c) // 画像の左側
65 img.Set(img.Rect.Max.X-1-offset, y, c) // 画像の右側
66 }
67 }
68}
コードを実行すると下記のように赤枠がついた画像が生成されます。