How I can combine images PNG and keep their transparency?

Hi.

I’m trying to combine multiple images to create a new image.

The problem is that when a PNG image is on another image is seen a black background.

How I can combine images PNG and keep their transparency ?

In this example the image 1 is JPG and image 2 is PNG .

IMG 1 - JPG

IMG 2 - PNG

The Code:

package main

import (
“image”
“image/draw”
“image/jpeg”
“image/png”
“log”
“os”
//“code.google.com/p/graphics-go/graphics
)

func main() {
fImg1, err := os.Open(“img4.png”)
if err != nil {
log.Println(“Error abriendo”, err)
}
defer fImg1.Close()
img1, err := png.Decode(fImg1)
if err != nil {
log.Println(“Error Decodificando”, err)
}

fImg2, _ := os.Open("img2.jpg")
defer fImg2.Close()
img2, _, _ := image.Decode(fImg2)

m := image.NewRGBA(image.Rect(0, 0, 3000, 3000))
draw.Draw(m, m.Bounds(), img2, image.Point{0, 0}, draw.Src)
//draw.Draw(m, m.Bounds(), img1, image.Point{1000, 1000}, draw.Src)
draw.Draw(m, m.Bounds(), img1, image.Point{-200, -200}, draw.Src)
//graphics.Rotate(m, img2, &graphics.RotateOptions{3.5})

toimg, _ := os.Create("new.jpg")
defer toimg.Close()

jpeg.Encode(toimg, m, nil)

}

1 Like

Help please

try draw.Over for the PNG, instead of draw.Src – i think it will work :smile:

1 Like

Could you explain how to use OVER XD

The last parameter in draw.Draw() is “op”…

For “op” you can choose draw.Src or draw.Over. If you choose draw.Src, then draw.Draw() doesn’t keep transparency. If you choose draw.Over, then it does!

So try changing:

draw.Draw(m, m.Bounds(), img1, image.Point{-200, -200}, draw.Src)

to:

draw.Draw(m, m.Bounds(), img1, image.Point{-200, -200}, draw.Over)

and see if it works :smiley:

2 Likes

Perfect

Thanks :grinning:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.