二维码(去白边区域)

package com.texwinca.HRM.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class BarcodeUtil {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    /*path:路徑
     *content:內容
     *height:高度
     *width:寬度
     *format:格式
     * */
    public static String getBarcode(String path,String content,int height,int width,String format) throws WriterException, IOException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        bm = deleteWhite(bm);
        BufferedImage image = toImage(bm);
        File file =new File(path);
        if(file.exists()){
            file.delete();
        }
        FileOutputStream output = new FileOutputStream(path);
        ImageIO.write(image, format, output);
        return "";
    }
 
 private static BufferedImage toImage(BitMatrix bm){
     int width = bm.getWidth();
     int height = bm.getHeight();
     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     for(int x = 0;x < width; x++){
         for(int y = 0; y < height; y++ ){
             image.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
         }
       }
     return image;
 }
 
 private static BitMatrix deleteWhite(BitMatrix matrix) {
     int[] rec = matrix.getEnclosingRectangle();
     int resWidth = rec[2] + 1;
     int resHeight = rec[3] + 1;
     BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
     resMatrix.clear();
     for (int i = 0; i < resWidth; i++) {
         for (int j = 0; j < resHeight; j++) {
             if (matrix.get(i + rec[0], j + rec[1]))
                 resMatrix.set(i, j);
         }
     }
     return resMatrix;
 }
 public static void main(String[] args) {
     try {
         BarcodeUtil.getBarcode("D://TESE.JPG","12345",90,90,"JPG");
    } catch (WriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }
}

你可能感兴趣的:(java)