实现说明
image/png 图像编解码可以归结为函数 main。
驱动整个流程的是 for y := 0; y < 3; y++ 这一个循环。没有静默穿透——中途有 2 个检查点测试 err != nil。
使用要点
- 演示输出是带标签的(
encode failed:、png bytes:、magic:),每个操作都会留下自己的一行标注。
常见问题
运行「image/png 图像编解码」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 encode failed:、png bytes:、magic: 标签标明各步骤。
核心语句
if err != nil {
fmt.Println("decode failed:", err)
return
}
代码示例
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)
}