github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/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 "encoding/base64" 9 "fmt" 10 "image" 11 "image/color" 12 "image/png" 13 "io" 14 "log" 15 "os" 16 "strings" 17 ) 18 19 const gopher = `iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwUVRzHf2+OPbo9d7tsWyiyaZti6eWGAhISoIGKECEKCAiJJkYTiUgTMYSIosYYBBIUIxoSPIINEBDi2VhwkQrVsj1ESgu9doHWdrul7ba73WNm3vOPtsseM9MdwvvrzTs+8/t95ze/33sI5BqiabU6m9En8oNjduLnAEDLUsQXFF8tQ5oxK3vmnNmDSMtrncks9Hhtt/qeWZapHb1ha3UqYSWVl2ZmpWgaXMXGohQAvmeop3bjTRtv6SgaK/Pb9/bFzUrYslbFAmHPp+3WhAYdr+7GN/YnpN46Opv55VDsJkoEpMrY/vO2BIYQ6LLvm0ThY3MzDzzeSJeeWNyTkgnIE5ePKsvKlcg/0T9QMzXalwXMlj54z4c0rh/mzEfr+FgWEz2w6uk8dkzFAgcARAgNp1ZYef8bH2AgvuStbc2/i6CiWGj98y2tw2l4FAXKkQBIf+exyRnteY83LfEwDQAYCoK+P6bxkZm/0966LxcAAILHB56kgD95PPxltuYcMtFTWw/FKkY/6Opf3GGd9ZF+Qp6mzJxzuRSractOmJrH1u8XTvWFHINNkLQLMR+XHXvfPPHw967raE1xxwtA36IMRfkAAG29/7mLuQcb2WOnsJReZGfpiHsSBX81cvMKywYZHhX5hFPtOqPGWZCXnhWGAu6lX91ElKXSalcLXu3UaOXVay57ZSe5f6Gpx7J2MXAsi7EqSp09b/MirKSyJfnfEEgeDjl8FgDAfvewP03zZ+AJ0m9aFRM8eEHBDRKjfcreDXnZdQuAxXpT2NRJ7xl3UkLBhu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 // gopherPNG creates an io.Reader by decoding the base64 encoded image data string in the gopher constant. 22 func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) } 23 24 func ExampleDecode() { 25 // This example uses png.Decode which can only decode PNG images. 26 // Consider using the general image.Decode as it can sniff and decode any registered image format. 27 img, err := png.Decode(gopherPNG()) 28 if err != nil { 29 log.Fatal(err) 30 } 31 32 levels := []string{" ", "░", "▒", "▓", "█"} 33 34 for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { 35 for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { 36 c := color.GrayModel.Convert(img.At(x, y)).(color.Gray) 37 level := c.Y / 51 // 51 * 5 = 255 38 if level == 5 { 39 level-- 40 } 41 fmt.Print(levels[level]) 42 } 43 fmt.Print("\n") 44 } 45 } 46 47 func ExampleEncode() { 48 const width, height = 256, 256 49 50 // Create a colored image of the given width and height. 51 img := image.NewNRGBA(image.Rect(0, 0, width, height)) 52 53 for y := 0; y < height; y++ { 54 for x := 0; x < width; x++ { 55 img.Set(x, y, color.NRGBA{ 56 R: uint8((x + y) & 255), 57 G: uint8((x + y) << 1 & 255), 58 B: uint8((x + y) << 2 & 255), 59 A: 255, 60 }) 61 } 62 } 63 64 f, err := os.Create("image.png") 65 if err != nil { 66 log.Fatal(err) 67 } 68 69 if err := png.Encode(f, img); err != nil { 70 f.Close() 71 log.Fatal(err) 72 } 73 74 if err := f.Close(); err != nil { 75 log.Fatal(err) 76 } 77 }