Golang如何创建RGB图像(非RGBA格式)
Golang如何创建RGB图像(非RGBA格式) 如何创建RGB图像(而非RGBA)?我决定学习Go语言进行图像处理。但我发现只能创建RGBA图像,这让我感到困惑。为什么没有NewRGB函数?我想写入不带Alpha通道的PNG图像。
1 回复
更多关于Golang如何创建RGB图像(非RGBA格式)的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中创建RGB图像(非RGBA)可以通过image.RGBA类型配合忽略Alpha通道实现,或者使用image.NRGBA类型。以下是两种方法:
方法1:使用image.RGBA并设置Alpha为255
package main
import (
"image"
"image/png"
"os"
)
func main() {
// 创建RGBA图像(宽度100,高度100)
img := image.NewRGBA(image.Rect(0, 0, 100, 100))
// 填充RGB像素(设置Alpha为255表示不透明)
for y := 0; y < 100; y++ {
for x := 0; x < 100; x++ {
// 设置颜色:R=100, G=200, B=300, A=255(完全不透明)
img.SetRGBA(x, y, color.RGBA{100, 200, 300, 255})
}
}
// 保存为PNG
f, _ := os.Create("rgb_image.png")
png.Encode(f, img)
f.Close()
}
方法2:使用image.NRGBA(直接存储RGB)
package main
import (
"image"
"image/color"
"image/png"
"os"
)
func main() {
// 创建NRGBA图像
img := image.NewNRGBA(image.Rect(0, 0, 100, 100))
// 填充RGB像素(无需处理Alpha)
for y := 0; y < 100; y++ {
for x := 0; x < 100; x++ {
// NRGBA直接存储RGB值,Alpha独立
img.Set(x, y, color.NRGBA{100, 200, 300, 255})
}
}
// 保存PNG(编码器会自动处理)
f, _ := os.Create("nrgba_image.png")
png.Encode(f, img)
f.Close()
}
方法3:自定义RGB图像类型
package main
import (
"image"
"image/color"
"image/png"
"os"
)
// 自定义RGB图像结构
type RGBImage struct {
Pix []uint8
Stride int
Rect image.Rectangle
}
func NewRGBImage(r image.Rectangle) *RGBImage {
w, h := r.Dx(), r.Dy()
return &RGBImage{
Pix: make([]uint8, 3*w*h),
Stride: 3 * w,
Rect: r,
}
}
func (img *RGBImage) ColorModel() color.Model {
return color.RGBAModel
}
func (img *RGBImage) Bounds() image.Rectangle {
return img.Rect
}
func (img *RGBImage) At(x, y int) color.Color {
if !(image.Point{x, y}.In(img.Rect)) {
return color.RGBA{}
}
i := (y-img.Rect.Min.Y)*img.Stride + (x-img.Rect.Min.X)*3
return color.RGBA{
R: img.Pix[i],
G: img.Pix[i+1],
B: img.Pix[i+2],
A: 255,
}
}
func (img *RGBImage) Set(x, y int, c color.Color) {
if !(image.Point{x, y}.In(img.Rect)) {
return
}
i := (y-img.Rect.Min.Y)*img.Stride + (x-img.Rect.Min.X)*3
r, g, b, _ := c.RGBA()
img.Pix[i] = uint8(r >> 8)
img.Pix[i+1] = uint8(g >> 8)
img.Pix[i+2] = uint8(b >> 8)
}
func main() {
// 使用自定义RGB图像
img := NewRGBImage(image.Rect(0, 0, 100, 100))
// 设置像素颜色
img.Set(50, 50, color.RGBA{255, 0, 0, 255})
// 保存为PNG
f, _ := os.Create("custom_rgb.png")
png.Encode(f, img)
f.Close()
}
PNG编码器会正确处理这些图像类型。image.NRGBA是最接近RGB的格式,它存储独立的Alpha通道,但编码为PNG时会自动优化。

