Encode Images With image/png
Build a gradient image in memory, encode it with image/png, and decode the bytes back to verify dimensions and pixel values.
Code
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"image/png"
)
func main() {
img := image.NewRGBA(image.Rect(0, 0, 4, 3))
for y := 0; y < 3; y++ {
for x := 0; x < 4; x++ {
// 用坐标生成可预测的渐变颜色
img.Set(x, y, color.RGBA{R: uint8(x * 60), G: uint8(y * 80), B: 0xCC, A: 0xFF})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
fmt.Println("encode failed:", err)
return
}
fmt.Println("png bytes:", buf.Len())
fmt.Println("magic:", buf.Bytes()[1:4])
// Decode 读回图像并检查边界与像素
decoded, err := png.Decode(bytes.NewReader(buf.Bytes()))
if err != nil {
fmt.Println("decode failed:", err)
return
}
bounds := decoded.Bounds()
fmt.Println("bounds:", bounds.Dx(), "x", bounds.Dy())
r, g, b, a := decoded.At(3, 2).RGBA()
fmt.Printf("pixel(3,2): r=%d g=%d b=%d a=%d\n", r>>8, g>>8, b>>8, a>>8)
}Inside the snippet
Encode Images With image/png keeps everything in the function main.
Iteration happens inside for y := 0; y < 3; y++ — everything outside it runs once. Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Using it
The run emits 6 labeled sections — encode failed:, png bytes:, magic:, decode failed:, bounds:, pixel(3,2): r= — one per step.
Key statements
if err != nil {
fmt.Println("decode failed:", err)
return
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What does Encode Images With image/png print when run?
- Running the file directly is enough — expect labeled output lines such as `encode failed:`, `png bytes:`, `magic:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.