JBarcode生成条形码(带汉字)

版权声明:学习 https://blog.csdn.net/qq_40238006/article/details/84542035

 JBarcode生成条形码(带汉字);请注意Maven里面现在没有这个jar报的依赖,需要自己下载,并手动导入Maven


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.jbarcode.JBarcode;
import org.jbarcode.JBarcodeFactory;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.TextPainter;
import org.jbarcode.util.ImageUtil;

public class JBarcodeUtil {
	
	// 设置条形码高度
	private static final int BARCODE_HEIGHT = 50;
	// 设置条形码默认分辨率
	//private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
	private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
	// 设置条形码字体样式
	//private static final String FONT_FAMILY = "微软雅黑";
	//private static final String FONT_FAMILY = "STXihei";
	private static final String FONT_FAMILY = "Microsoft YaHei";
	// 设置条形码字体大小
	private static final int FONT_SIZE = 14;
	// 设置条形码文本
	/*public static String TEXTONE = "";
	public static String TEXTTWO = "";
	public static String TEXTTHREE = "";*/
	public static String TEXT = "";
	// 创建jbarcode
	private static JBarcode jbc = null;

	/**
	 * 1.静态代码块的作用:当类被载入时,静态代码块被执行,且只被执行一次,静态块常用来执行类属性的初始化。  
     * 2.常量条形码的高度和字体大小设置很重要,若是设置小了会看不到设置的文件 
	 * @return
	 * @throws InvalidAtributeException
	 */
	static JBarcode getJBarcode() throws InvalidAtributeException {
		/**
		 * 参考设置样式:
		 * barcode.setEncoder(Code128Encoder.getInstance()); //设置编码
		 * barcode.setPainter(WidthCodedPainter.getInstance());// 设置Painter
		 * barcode.setTextPainter(BaseLineTextPainter.getInstance()); //设置TextPainter
		 * barcode.setBarHeight(17); //设置高度
		 * barcode.setWideRatio(Double.valueOf(30).doubleValue());// 设置宽度比率
		 * barcode.setXDimension(Double.valueOf(2).doubleValue()); // 设置尺寸,大小 密集程度
		 * barcode.setShowText(true); //是否显示文本 
		 * barcode.setCheckDigit(true); //是否检查数字
		 * barcode.setShowCheckDigit(false); //是否显示检查数字
		 */
		if (jbc == null) {
			// 	生成code128
			jbc = JBarcodeFactory.getInstance().createCode128();
			jbc.setEncoder(Code128Encoder.getInstance());
			//	设置TextPainter
			jbc.setTextPainter(CustomTextPainter.getInstance());
			//	设置设置条形码高度
			jbc.setBarHeight(BARCODE_HEIGHT);
			//	设置尺寸,大小 密集程度
			jbc.setXDimension(Double.valueOf(0.8).doubleValue());
			//	是否显示文本 
			jbc.setShowText(true);
		}
		return jbc;
	}

	/**
	 * @descript:		生成条形码文件(调用此方法进行生成工作)
	 * @param message	显示的文字内容
	 * @param file		生成文件地址
	 * @param content	条形码内容
	 * @return 
	 */
	public static String createBarcode(String message, File file, String content) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			createBarcode(message, fos, content);
			fos.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return "scuccs";
	}

	/**
	 * @descript:		生成条形码并写入指定输出流
	 * @param message	条形码内容
	 * @param os		输出流
	 * @param text		文字内容
	 */
	private static void createBarcode(String message, OutputStream os, String text) {
		try {
			/*String[]  strs = text.split("-");
			// 设置条形码文本
			switch(strs.length){
			case 1:
				TEXTONE = strs[0].toString();
				TEXTTWO = "";
				TEXTTHREE = "";
			    break;
			case 2:
				TEXTONE = strs[0].toString();
				TEXTTWO = strs[1].toString();
				TEXTTHREE = "";
			    break;
			default:
				TEXTONE = strs[0].toString();
				TEXTTWO = strs[1].toString();
				TEXTTHREE = strs[2].toString();
			    break;
			}*/
			int lenght = message.length();
			String zero = "";
			for (int i = lenght; i < 7; i++) {
				zero += "0";
			}
			message = zero + message;
			
			TEXT = text;
			// 创建条形码的BufferedImage图像
			BufferedImage image = getJBarcode().createBarcode(message);
			/*int a = image.getWidth();
			int b = image.getHeight();
			System.out.println("生成的图片:宽为"+a+"、高为"+b);*/
			
			ImageUtil.encodeAndWrite(image, ImageUtil.PNG, os, BARCODE_DPI, BARCODE_DPI);
			os.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 静态内部类 自定义的 TextPainter, 允许定义字体,大小,文本等
	 * 参考底层实现:BaseLineTextPainter.getInstance()
	 */
	private static class CustomTextPainter implements TextPainter {
		private static CustomTextPainter instance = new CustomTextPainter();

		public static CustomTextPainter getInstance() {
			return instance;
		}

		public void paintText(BufferedImage barCodeImage, String text, int width) {
			// 绘图
			Graphics g2d = barCodeImage.getGraphics();
			// 创建字体
			Font font = new Font(FONT_FAMILY, Font.PLAIN, FONT_SIZE * width);
			g2d.setFont(font);
			//g2d.drawRect(0, 0, 500, 500);
			FontMetrics fm = g2d.getFontMetrics();
			//	高度
			int height = fm.getHeight();
			//	中心	这里的text是指的条形码数字
			int center = (barCodeImage.getWidth() - fm.stringWidth(text)) / 2 + 10;
			
			/*int a = (barCodeImage.getWidth() - fm.stringWidth(TEXTONE)) / 2;
			int b = (barCodeImage.getWidth() - fm.stringWidth(TEXTTWO)) / 2;
			int c = (barCodeImage.getWidth() - fm.stringWidth(TEXTTHREE)) / 2;*/
			int d = (barCodeImage.getWidth() - fm.stringWidth(TEXT)) / 2;
			
			//	条形内容上下的颜色
			g2d.setColor(Color.WHITE);
			//	条形码-----码的上部
			//g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() * 1 / 20);
			g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() * 7 / 20);
			
			//	条形码-----码的底部
			g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10), barCodeImage.getWidth(), (height * 9 / 10));
			
			//	显示的字体颜色(包括条形码下方的数字)
			g2d.setColor(Color.BLACK);
			// 	绘制文本
			/*g2d.drawString(TEXTONE, a, 145);
			g2d.drawString(TEXTTWO, b, 170);
			g2d.drawString(TEXTTHREE, c, 195);*/
			g2d.drawString(TEXT, d, 30);
			//	绘制安保或者涉案字样
			g2d.drawString("SA", 16, 55);
			// 绘制条形码的数字内容
			//g2d.drawString(text, center, barCodeImage.getHeight() - (height / 10) - 2);//在最下面
			g2d.drawString(text, center, 55);//在中间
		}
	}
	
	public static void main(String[] args) {
		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(50);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8, 1, TimeUnit.DAYS, queue);
		Long data = new Date().getTime();
		String datas = data.toString();
		List<File> fileList = new ArrayList<File>();
		// 存放地址
		File newImagepath = new File("d:/" + datas + ".jpg");
		fileList.add(newImagepath);
		// 生成条形码的内容
		String content = "6";
		// 显示在条形码上的文字
		String text = "第04箱";
		try {
			if (executor.getQueue().size() > 30) {
				Thread.sleep(200);
			}
			// 生成条形码的方法
			MultithreadForBarCod barCode = new MultithreadForBarCod();
			barCode.setMessage(content);
			barCode.setFile(newImagepath);
			barCode.setText(text);

			executor.execute(barCode);
			Thread.sleep(20);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		executor.shutdown();
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_40238006/article/details/84542035