github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/image/decode_example_test.go (about) 1 // Copyright 2012 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 // This example demonstrates decoding a JPEG image and examining its pixels. 6 package image_test 7 8 import ( 9 "github.com/shogo82148/std/encoding/base64" 10 "github.com/shogo82148/std/fmt" 11 "github.com/shogo82148/std/image" 12 "github.com/shogo82148/std/log" 13 "github.com/shogo82148/std/strings" 14 ) 15 16 func Example_decodeConfig() { 17 reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) 18 config, format, err := image.DecodeConfig(reader) 19 if err != nil { 20 log.Fatal(err) 21 } 22 fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format) 23 } 24 25 func Example() { 26 // JPEGデータをデコードします。ファイルから読み取る場合は、リーダーを作成します 27 // 28 // reader, err := os.Open("testdata/video-001.q50.420.jpeg") 29 // if err != nil { 30 // log.Fatal(err) 31 // } 32 // defer reader.Close() 33 reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) 34 m, _, err := image.Decode(reader) 35 if err != nil { 36 log.Fatal(err) 37 } 38 bounds := m.Bounds() 39 40 // mの赤、緑、青、アルファ成分の16ビンヒストグラムを計算します。 41 // 42 // 画像の境界は必ずしも(0, 0)から始まるわけではないので、2つのループは 43 // bounds.Min.Yとbounds.Min.Xから始まります。Yを最初に、Xを次にループする方が、 44 // Xを最初に、Yを次にループするよりも、より良いメモリアクセスパターンになる可能性が高いです。 45 var histogram [16][4]int 46 for y := bounds.Min.Y; y < bounds.Max.Y; y++ { 47 for x := bounds.Min.X; x < bounds.Max.X; x++ { 48 r, g, b, a := m.At(x, y).RGBA() 49 // 色のRGBAメソッドは、範囲[0, 65535]の値を返します。 50 // これを12ビット右シフトすると、範囲が[0, 15]に縮小されます。 51 histogram[r>>12][0]++ 52 histogram[g>>12][1]++ 53 histogram[b>>12][2]++ 54 histogram[a>>12][3]++ 55 } 56 } 57 58 // 結果を表示します。 59 fmt.Printf("%-14s %6s %6s %6s %6s\n", "bin", "red", "green", "blue", "alpha") 60 for i, x := range histogram { 61 fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3]) 62 } 63 // Output: 64 // bin red green blue alpha 65 // 0x0000-0x0fff: 364 790 7242 0 66 // 0x1000-0x1fff: 645 2967 1039 0 67 // 0x2000-0x2fff: 1072 2299 979 0 68 // 0x3000-0x3fff: 820 2266 980 0 69 // 0x4000-0x4fff: 537 1305 541 0 70 // 0x5000-0x5fff: 319 962 261 0 71 // 0x6000-0x6fff: 322 375 177 0 72 // 0x7000-0x7fff: 601 279 214 0 73 // 0x8000-0x8fff: 3478 227 273 0 74 // 0x9000-0x9fff: 2260 234 329 0 75 // 0xa000-0xafff: 921 282 373 0 76 // 0xb000-0xbfff: 321 335 397 0 77 // 0xc000-0xcfff: 229 388 298 0 78 // 0xd000-0xdfff: 260 414 277 0 79 // 0xe000-0xefff: 516 428 298 0 80 // 0xf000-0xffff: 2785 1899 1772 15450 81 }