JAvaは二次元コードの符号化と復号化を実現する

3674 ワード

本稿で実現するQRコードの操作はgoogleのzxingに依存し、追加するjarパッケージはcore.jarとjavase.jar
依存するクラスは次のとおりです.
import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

QRコード:

/**
     *  
     * @param str   
     * @return
     */
    @SuppressWarnings("unchecked")
    public static File encode(String str) {
        try {
            SimpleDateFormat sdDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String path = "./encode" + sdDateFormat.format(new Date()) + ".png";
            int width = 180;  
            int height = 160; 
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix byteMatrix;
            byteMatrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, width, height,hints);
            File file = new File(path);
            MatrixToImageWriter.writeToFile(byteMatrix, "png", file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

QRコードの復号化:

/**
     *  
     * @param file    ( )
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Result decode(File file) {
        try {
            BufferedImage image;
            try {
                image = ImageIO.read(file);
                if (image == null) {
                    System.out.println("Could not decode image");
                }
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
                        source));
                Result result;
                Hashtable hints = new Hashtable();
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                result = new MultiFormatReader().decode(bitmap, hints);
                return result;
            } catch (IOException ioe) {
                System.out.println(ioe.toString());
                return null;
            } catch (ReaderException re) {
                System.out.println(re.toString());
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }