如何生成一维码

需要:jar:jbarcode-0.2.8.jar

欢迎加入QQ群交流:1群已满,请加2群466355109,技术不全没关系,只要有交流的心就尽管来吧!!

/**
 * 
 * 一维码图片生成器
 * @author winter.liu
 *
 */
public class OneBarcodeUtil {
	
	
	/**
	 * 生成一维码
	 * @param value 值
	 * @return
	 */
	public static byte[] createBarcodeDefault(String value){
		return createBarcode(Code39Encoder.class,value,false);
	}
	
	//产生一维码图片
	public static byte[] createBarcode(Class<?> clazz,String value,boolean checkDigit){
		  try{
			  JBarcode localJBarcode = new JBarcode(getInstance(clazz),WidthCodedPainter.getInstance(),EAN13TextPainter.getInstance());  
		      localJBarcode.setPainter(WideRatioCodedPainter.getInstance());  
		      localJBarcode.setTextPainter(BaseLineTextPainter.getInstance());  
		      localJBarcode.setCheckDigit(checkDigit);
		      localJBarcode.setShowCheckDigit(checkDigit);
		      return getBytes(localJBarcode.createBarcode(value));  
		  }catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//获取单例的对象
	private static BarcodeEncoder getInstance(Class<?> clazz) throws Exception{
		Constructor<?>[] constructors=clazz.getDeclaredConstructors();
		Constructor<?> privateConstructor = constructors[0];
		privateConstructor.setAccessible(true);
		return (BarcodeEncoder)privateConstructor.newInstance();
		
	}
	
	//获取图片字节码数组
	private static byte[] getBytes(BufferedImage paramBufferedImage) throws IOException{  
	      return ImageUtil.encode(paramBufferedImage,"jpeg", 96, 96);
	}  


}

你可能感兴趣的:(java,springMVC,图片,jar,一维码)