Golang image.Alpha.Bounds function examples

package image

 func (p *Alpha) Bounds() Rectangle
  

Golang image.Alpha.Bounds function usage examples

Example 1:

 package main

 import (
 "fmt"
 "image"
 "image/jpeg"
 "os"
 )

 func init() {
 // damn important or else At(), Bounds() functions will
 // caused memory pointer error!!
 image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
 }

 func main() {
 imgfile, err := os.Open("./img.jpg")

 if err != nil {
 fmt.Println("img.jpg file not found!")
 os.Exit(1)
 }

 defer imgfile.Close()

 img, _, err := image.Decode(imgfile)

 fmt.Println(img.At(10, 10))

 bounds := img.Bounds() // <-- here

 fmt.Println(bounds)

 canvas := image.NewAlpha(bounds)

 // is this image opaque
 op := canvas.Opaque()

 fmt.Println(op)
 }

Output(sample, depending on your image file content) :

{255 128 128}

(0,0)-(760,479)

false

Example 2:

 // textBox renders t into a tight fitting image
 func (ig *ImageGraphics) textBox(t string, font chart.Font) image.Image {
  // Initialize the context.
  fg := image.NewUniform(color.Alpha{0xff})
  bg := image.NewUniform(color.Alpha{0x00})
  width := ig.TextLen(t, font)
  size := ig.relFontsizeToPixel(font.Size)
  bb := ig.font.Bounds(int32(size))
  // TODO: Ugly, manual, heuristic hack to get "nicer" text for common latin characters
  bb.YMin++
  if size >= 15 {
 bb.YMin++
 bb.YMax--
  }
  if size >= 20 {
 bb.YMax--
  }
  if size >= 25 {
 bb.YMin++
 bb.YMax--
  }
  dy := int(bb.YMax - bb.YMin)
  canvas := image.NewAlpha(image.Rect(0, 0, width, dy))
  draw.Draw(canvas, canvas.Bounds(), bg, image.ZP, draw.Src) // <-- here
  c := freetype.NewContext()
  c.SetDPI(dpi)
  c.SetFont(ig.font)
  c.SetFontSize(size)
  c.SetClip(canvas.Bounds()) // <-- here
  c.SetDst(canvas)
  c.SetSrc(fg)
  // Draw the text.
  pt := freetype.Pt(0, dy+int(bb.YMin)-1)
  extent, err := c.DrawString(t, pt)
  if err != nil {
 log.Println(err)
 return nil
  }
  // log.Printf("text %q, extent: %v", t, extent)
  return canvas.SubImage(image.Rect(0, 0, int((extent.X+127)/256), dy))
 }

References :

https://github.com/vdobler/chart/blob/master/imgg/image.go

http://golang.org/pkg/image/#Alpha.Bounds

Advertisement