Golang : How to read JPG(JPEG), GIF and PNG files ?
Was having a hard time trying to figure out why all my attempts to open and read JPG or JPEG format image files will cause memory pointer error(when trying to get At() and Bounds() functions to work).
Apparently, in Golang, one must register the format in the init() section first before attempting to open/read image files and perform operation on the files.
The code below is a simple guide on how to open and read JPEG/JPG format image files :
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()
fmt.Println(bounds)
canvas := image.NewAlpha(bounds)
// is this image opaque
op := canvas.Opaque()
fmt.Println(op)
}
Sample output :
{255 128 128}
(0,0)-(760,479)
false
This should apply to the PNG and GIF encoded images as well. ( see https://www.socketloop.com/references/golang-image-registerformat-function-example )
See also : Golang : Save image to PNG, JPEG or GIF format.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Golang : List running EC2 instances and descriptions
+6.2k Golang : Experimental emojis or emoticons icons programming language
+9.6k Golang : Check a web page existence with HEAD request example
+26.2k Golang : How to check if a connection to database is still alive ?
+15k Golang : Get checkbox or extract multipart form data value example
+15.6k Golang : How to check if input from os.Args is integer?
+4.6k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+7k Golang : Rot13 and Rot5 algorithms example
+16.8k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+6.5k Golang : Takes a plural word and makes it singular
+12.5k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.7k Golang : Dealing with backquote