I'm trying to import 2 png image and paste one on top of the other. The output will be jpeg.
When ever I run the code below, I got this error:
image: unknown format
image: unknown format
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x109d7a4]
goroutine 1 [running]:
main.main()
Error is coming whenever I use "Bounds()" method. What do you think is the cause.
code:
func main() {
imgFile1, err := os.Open("./pics/00/body.png")
if err != nil {
fmt.Println(err)
}
defer imgFile1.Close()
imgFile2, err := os.Open("./pics/01/face.png")
if err != nil {
fmt.Println(err)
}
defer imgFile2.Close()
img1, _, err := image.Decode(imgFile1)
if err != nil {
fmt.Println(err)
}
img2, _, err := image.Decode(imgFile2)
if err != nil {
fmt.Println(err)
}
//new rectangle for the second image
sp1 := image.Point{0,0}
sp2 := image.Point{img1.Bounds().Dx(),img1.Bounds().Dy()}
r2 := image.Rectangle{sp1, sp2}
//create new image
rgba := image.NewRGBA(r2)
//draw the two images into this new image
draw.Draw(rgba, r2, img1, image.Point{0, 0}, draw.Src)
draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)
//export it
out, err := os.Create("./output.jpg")
if err != nil {
fmt.Println(err)
}
defer out.Close()
var opt jpeg.Options
opt.Quality = 80
jpeg.Encode(out, rgba, &opt)
}
CodePudding user response:
Im not sure why Go has two ways to decode like this. If you know the file type, I think its better to just use the specific package:
package main
import (
"fmt"
"image/png"
"net/http"
)
const ava = "http://gravatar.com/avatar/5ec9c21c8d54825b04def7a41998d18d"
func main() {
r, err := http.Get(ava)
if err != nil {
panic(err)
}
defer r.Body.Close()
i, err := png.Decode(r.Body)
if err != nil {
panic(err)
}
dx := i.Bounds().Dx()
fmt.Println(dx)
}
If you insist on using the other method, you will need to add an import (thanks to mkopriva):
import (
"image"
_ "image/png"
)