Kumar Swapnil
Kumar Swapnil

Reputation: 190

Golang Overlay image always black and white

I am trying to put an overlay on qrcode(image). The problem is my original overlay image is colored but the end result is black and white. Below is the code:

func (e Encoder) Encode(str string, logo image.Image, size int) (*bytes.Buffer, error) {
    var buf bytes.Buffer

    code, err := qr.New(str, e.QRLevel)
    if err != nil {
        return nil, err
    }

    img := code.Image(size)
    e.overlayLogo(img, logo)

    err = png.Encode(&buf, img)
    if err != nil {
        return nil, err
    }

    return &buf, nil
}


func (e Encoder) overlayLogo(dst, src image.Image) {

    offset := dst.Bounds().Max.X/2 - src.Bounds().Max.X/2
    yOffset := dst.Bounds().Max.Y/2 - src.Bounds().Max.Y/2
    draw.Draw(dst.(draw.Image), dst.Bounds().Add(image.Pt(offset, yOffset)), src, image.Point{}, draw.Over)
}

Can someone please help me here? This is the final image that I'm getting

Image Used

Upvotes: 3

Views: 1101

Answers (2)

papawin
papawin

Reputation: 1

My work needs it too. So from @icza I summarized :-

resultImg := image.NewRGBA(qrImg.Bounds())
overlayLogo(resultImg, qrImg)
overlayLogo(resultImg, logo)

So we get the resultImg, QR code with logo.

Upvotes: 0

icza
icza

Reputation: 417612

QR code images use 2 colors which makes them easier to scan / recognize. The library you're using github.com/skip2/go-qrcode creates paletted images that use 2 colors only (black and white by default). You can check the source code of QRCode.Image() method you're calling, source here:

p := color.Palette([]color.Color{q.BackgroundColor, q.ForegroundColor})
img := image.NewPaletted(rect, p)

This means whatever you draw on such images, color for each pixel will be chosen from this 2-sized palette (either back or white). The color information of the drawn image will be lost.

If you want to retain all the colors, you must create an image that supports all (or at least the used) colors, draw the QR code image on that, and then the overlay.

Upvotes: 2

Related Questions