makiuchi-d / gozxing

Port of ZXing (https://github.com/zxing/zxing) core to pure Go.
Other
564 stars 65 forks source link

QR decoding of this file does not find a code. Scanners (Android, online) find it. #56

Closed wunderbarb closed 1 year ago

wunderbarb commented 1 year ago

The attached PNG file cannot be detected by the lib. What am I doing wrong?


func Decode(data []byte) (string, error) {
    img, err := png.Decode(bytes.NewReader(data))
    if err != nil {
        return "", ErrNotPNG
    }
    // prepare BinaryBitmap
    bmp, err := gozxing.NewBinaryBitmapFromImage(img)
    if err != nil {
        return "", ErrNotPNG
    }
    // decode image
    qrReader := qr1.NewQRCodeReader()
    result, err := qrReader.Decode(bmp, nil)
    if err != nil {
        return "", ErrNotQRCode
    }
    return result.GetText(), nil
}```
![qr](https://user-images.githubusercontent.com/39924160/227664064-a9c716f0-1907-49da-8f15-3a60cb2a0150.png)
makiuchi-d commented 1 year ago

I got a result with DecodeHintType_PURE_BARCODE.

    result, err := qrReader.Decode(bmp, map[gozxing.DecodeHintType]any{
        gozxing.DecodeHintType_PURE_BARCODE: true,
    })

The online decoder is trying several DecodeHintType patterns and there is a pattern contains DecodeHintType.PURE_BARCODE. https://github.com/zxing/zxing/blob/master/zxingorg/src/main/java/com/google/zxing/web/DecodeServlet.java#L113

wunderbarb commented 1 year ago

Thanks Makiuchi-san. It works perfectly. I understand now the role of the hints. May I suggest that you provide an example using it in the documentation? This may help users. Following is a piece of code that uses your code with the hints.

// Decode attempts to extract the qrcode from `data`.  `data` is expected to be a raw png
// image.  The function tries several strategies to decode in increasing order of processing time.
func Decode(data []byte) (string, error) {
    img, err := png.Decode(bytes.NewReader(data))
    if err != nil {
        return "", ErrNotPNG
    }
    // prepare BinaryBitmap
    bmp, err := gozxing.NewBinaryBitmapFromImage(img)
    if err != nil {
        return "", ErrNotPNG
    }
    // decode image
    qrReader := qr1.NewQRCodeReader()
    result, err := qrReader.Decode(bmp, nil)
    if err == nil {
        return result.GetText(), nil
    }
    m := map[gozxing.DecodeHintType]any{
        gozxing.DecodeHintType_PURE_BARCODE: true,
    }
    result, err = qrReader.Decode(bmp, m)
    if err == nil {
        return result.GetText(), nil
    }
    m1 := map[gozxing.DecodeHintType]any{
        gozxing.DecodeHintType_TRY_HARDER: true,
    }
    result, err = qrReader.Decode(bmp, m1)
    if err != nil {
        return "", ErrNotQRCode
    }
    return result.GetText(), nil
}