Standard library provides the foundation for working with images.
Package image provides:
image.Image
interface describing a bitmap imageImage.RGBA
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:
package main
import (
"fmt"
"image/png"
"log"
"net/http"
)
// :show start
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)
}
// :show end
func main() {
showImageSize("<https://www.programming-books.io/covers/Go.png>")
}