github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/image/png/example_test.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package png_test 6 7 import ( 8 "github.com/shogo82148/std/fmt" 9 "github.com/shogo82148/std/image" 10 "github.com/shogo82148/std/image/color" 11 "github.com/shogo82148/std/image/png" 12 "github.com/shogo82148/std/log" 13 "github.com/shogo82148/std/os" 14 ) 15 16 func ExampleDecode() { 17 // この例では、PNG画像のみをデコードできるpng.Decodeを使用しています。 18 // 任意の登録済み画像フォーマットをスニフし、デコードできる一般的なimage.Decodeの使用を検討してください。 19 img, err := png.Decode(gopherPNG()) 20 if err != nil { 21 log.Fatal(err) 22 } 23 24 levels := []string{" ", "░", "▒", "▓", "█"} 25 26 for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { 27 for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { 28 c := color.GrayModel.Convert(img.At(x, y)).(color.Gray) 29 level := c.Y / 51 // 51 * 5 = 255 30 if level == 5 { 31 level-- 32 } 33 fmt.Print(levels[level]) 34 } 35 fmt.Print("\n") 36 } 37 } 38 39 func ExampleEncode() { 40 const width, height = 256, 256 41 42 // 与えられた幅と高さのカラー画像を作成します。 43 img := image.NewNRGBA(image.Rect(0, 0, width, height)) 44 45 for y := 0; y < height; y++ { 46 for x := 0; x < width; x++ { 47 img.Set(x, y, color.NRGBA{ 48 R: uint8((x + y) & 255), 49 G: uint8((x + y) << 1 & 255), 50 B: uint8((x + y) << 2 & 255), 51 A: 255, 52 }) 53 } 54 } 55 56 f, err := os.Create("image.png") 57 if err != nil { 58 log.Fatal(err) 59 } 60 61 if err := png.Encode(f, img); err != nil { 62 f.Close() 63 log.Fatal(err) 64 } 65 66 if err := f.Close(); err != nil { 67 log.Fatal(err) 68 } 69 }