ZhangZhihui's Blog  

The standard library for 2D image manipulation is the image package and the main interface is image.Image . To work with the different image formats, you need to register the format first by initializing the format’s package in the program’s main package:

import   _   "image/png"

Importing a package with an underscore allows you to create the package-level variables and also execute the init function in the image/png package. You can import more than one format; it doesn’t matter and the compiler won’t complain (because you’re naming it (“_”) — if you don’t name it, the compiler will complain).

The image.Image type is an interface that represents a rectangular grid of color.Color pixel values, taken from a color model. This is the main interface for the image package. Structs that implement this interface have to implement the ColorModel , Bounds , and At methods:

type Image interface {
    ColorModel() color.Model
    Bounds() Rectangle
    At(x, y int) color.Color
}

The color.Color interface has a method that returns the four values — red, green, blue, and alpha:

type Color interface {
    RGBA() (r, g, b, a uint32)
}

The color.Color interface represents a color. The At method in image.Image returns the color at the specific location at x, y.

An image.Rectangle is a rectangle defined by its top-left and bottom-right points, Min and Max , respectively:

type Rectangle struct {
    Min, Max Point
}

And finally, of course, an image.Point is a position defined by X and Y values:

type Point struct {
    X, Y int
}

 

Several structs implement image.Image in the same package. These include RGBA , NRGBA , Gray , CMYK , and NYCbCrA , to name a few. I’ll focus on NRGBA here because it’s easy to understand. Let’s talk a bit more about what RGBA and NRGBA mean.

The A in RGBA is the alpha channel (also called the image mask) that controls whether parts of the image are visible or not. The RGBA image is an image that is alpha-premultiplied or already has the alpha channel applied to it. The N in NRGBA means that the alpha channel is not applied to it. In other words, an NRGBA image is an image that has an alpha channel but it’s not premasked.

The alpha channel is used in a technique called alpha compositing , which combines two or more images into a final image called a composite. We won’t be doing compositing in this book but if you’re compositing images, the difference between having an alpha channel or not having an alpha channel is important. It’s also important if you are creating images with transparent backgrounds. Otherwise (meaning if the alpha channel is not used anyway) it doesn’t matter.

 

posted on 2023-10-10 09:50  ZhangZhihuiAAA  阅读(10)  评论(0编辑  收藏  举报