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 :
Advertisement
Something interesting
Tutorials
+5.3k Golang : Generate Interleaved 2 inch by 5 inch barcode
+19.9k Golang : Measure http.Get() execution time
+11.7k How to tell if a binary(executable) file or web application is built with Golang?
+20.5k Golang : Pipe output from one os.Exec(shell command) to another command
+8.3k Golang : Implementing class(object-oriented programming style)
+11.4k Golang : Delay or limit HTTP requests example
+13.7k Golang : Activate web camera and broadcast out base64 encoded images
+25.8k Golang : Daemonizing a simple web server process example
+7.5k Gogland : Single File versus Go Application Run Configurations
+25.4k Golang : Generate MD5 checksum of a file
+6.7k Golang : Skip or discard items of non-interest when iterating example
+6.5k Golang : Convert an executable file into []byte example