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.

GoData Integrity

Code

gosnippet
39 lines
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

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:`.