Images (PNG, JPEG, BMP, TIFF, WEBP, VP8, GIF)
suggest changeStandard library provides the foundation for working with images.
Package image provides:
- an
image.Image
interface describing a bitmap image - an implementation for most common ways of representing an image in memory, for example
Image.RGBA
- a way to register image format decoders (e.g. PNG, JPEG etc. with
image.RegisterFormat
.
Standard library provides:
The are libraries for:
The image.Image
interface is minimal:
type Image interface {
// ColorModel returns the Image's color model.
ColorModel() color.Model
// Bounds returns the domain for which At can return non-zero color.
// The bounds do not necessarily contain the point (0, 0).
Bounds() Rectangle
// At returns the color of the pixel at (x, y).
// At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
// At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
At(x, y int) color.Color
}
Here's an example of decoding a PNG image from an URL and printing the size of the image using Bounds()
method:
func showImageSize(uri string) {
resp, err := http.Get(uri)
if err != nil {
log.Fatalf("http.Get('%s') failed with %s\n", uri, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
log.Fatalf("http.Get() failed with '%s'\n", resp.Status)
}
img, err := png.Decode(resp.Body)
if err != nil {
log.Fatalf("png.Decode() failed with '%s'\n", err)
}
size := img.Bounds().Size()
fmt.Printf("Image '%s'\n", uri)
fmt.Printf(" size: %dx%d\n", size.X, size.Y)
fmt.Printf(" format in memory: '%T'\n", img)
}
Output:
Image 'https://www.programming-books.io/covers/Go.png'
size: 595x842
format in memory: '*image.NRGBA'
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents