QR Code encoding and decoding using zxing

前端 未结 6 2078
孤城傲影
孤城傲影 2020-11-27 10:05

Okay, so I\'m going to take the off chance that someone here has used zxing before. I\'m developing a Java application, and one of the things it needs to do is encode a byte

6条回答
  •  遥遥无期
    2020-11-27 10:48

    For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

    // ------------------------------------------------------------------------------------
    // Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
    // Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
    // Run with: groovy -cp "./lib/*" zxing.groovy
    // ------------------------------------------------------------------------------------
    
    import com.google.zxing.*
    import com.google.zxing.common.*
    import com.google.zxing.client.j2se.*
    
    import java.awt.image.BufferedImage
    import javax.imageio.ImageIO
    
    def class zxing {
        def static main(def args) {
            def filename = "./qrcode.png"
            def data = "This is a test to see if I can encode and decode this data..."
            def charset = "UTF-8" //"ISO-8859-1" 
            def hints = new Hashtable([(EncodeHintType.CHARACTER_SET): charset])
    
            writeQrCode(filename, data, charset, hints, 100, 100)
    
            assert data == readQrCode(filename, charset, hints)
        }
    
        def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
            BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
            MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
        }
    
        def static readQrCode(def filename, def charset, def hints) {
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
            Result result = new MultiFormatReader().decode(binaryBitmap, hints)
    
            result.getText()        
        }
    
    }
    

提交回复
热议问题