torsdag 16 januari 2014

Generate QRCode with Groovy

       


import com.google.zxing.*
import com.google.zxing.qrcode.*
import com.google.zxing.qrcode.decoder.*
import com.google.zxing.client.j2se.*
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.awt.*

//fix zxing dependency
@Grapes(
    @Grab(group='com.google.zxing', module='javase', version='2.2')
)

def QRCODE_IMAGE_HEIGHT = 300
def QRCODE_IMAGE_WIDTH = 300
//path where you want to save qrcode
def IMAGE_PATH = "C:/Users/luma/Google Drive/apps/"

def hints = new HashMap()
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H)
 
def qrWriter = new  QRCodeWriter()
//Add your data instead of http://capatosta.se/
def matrix = qrWriter.encode("http://capatosta.se/",
                         BarcodeFormat.QR_CODE,
                         QRCODE_IMAGE_WIDTH,
                         QRCODE_IMAGE_HEIGHT,
                         hints)
 
def image = MatrixToImageWriter.toBufferedImage(matrix)
//Read a logo gif to add QRCode image
def overlay = ImageIO.read(new File(IMAGE_PATH, "capa.gif"))
 
//Calculate the delta height and width
def deltaHeight = image.height - overlay.height
def deltaWidth  = image.width  - overlay.width 
 
//Draw the new image
def combined = new BufferedImage(QRCODE_IMAGE_HEIGHT, QRCODE_IMAGE_WIDTH, BufferedImage.TYPE_INT_ARGB)
def g = (Graphics2D)combined.getGraphics()
g.drawImage(image, 0, 0, null)
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f))
g.drawImage(overlay, (int)Math.round(deltaWidth/2), (int)Math.round(deltaHeight/2), null)
 
def imageFile = new File(IMAGE_PATH, "qrcode_logo2.png")
ImageIO.write(combined, "PNG", imageFile)
 
println "Generating QRCode ================================="
println "Image width,height: ${image.width},${image.height}"
println "Overlay width,height: ${overlay.width},${overlay.height}"
println "Delta width,height: $deltaWidth, $deltaHeight"
println "QRCode saved to: ${imageFile.absolutePath}"
println "DONE!! ================================="    

       
 

Inga kommentarer:

Skicka en kommentar