商品条形码生成图片(二)

转载地址:http://www.cnblogs.com/yuchuan/p/JBarcode2.html

(一)代码展示

package com.nicole.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code11Encoder;
import org.jbarcode.encode.EAN13Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;

/**
 * 简易生成条形码(EN-13码)
 *
 * @=============================================
 *
 * @author : Liuyc
 * @create : 2015-4-8 下午06:19:21
 * @update :
 * @bolg : http://www.cnblogs.com/yuchuan/
 * @csdn : http://blog.csdn.net/l_lycos
 * @E-mail : [email protected]
 * @desc :
 *
 * @=============================================
 */

public class TestBarcode {

	/**
	 * 生成商品条形码
	 *
	 * @param filePath
	 *            商品条形码图片存放路径:C://barcode//images//
	 *
	 * @param barCode
	 *            商品条形码:13位
	 * @param imgFormat
	 *            图片格式
	 * 
	 * @return 图片存放路径+图片名称+图片文件类型
	 */
	public static String createBarCode(String savePath, String jbarCode, String imgFormat) {

		// 校验全部省略……
		// if(StringUtils.isNotEmpty(savePath)){
		//

		// return null;
		// }
		// if(StringUtils.isNotEmpty(jbarCode)){
		// return null;
		// }
		// if(StringUtils.isNotEmpty

		// (imgFormat)){
		// return null;
		// }
		// if( jbarCode.length()!=13){
		// return null;
		// }

		try {

			BufferedImage bi = null;

			int len = jbarCode.length();

			// 实例化JBarcode
			// 这里三个参数,必要填写
			JBarcode jbarcode13 = new JBarcode(EAN13Encoder.getInstance(), WidthCodedPainter.getInstance(),
					EAN13TextPainter.getInstance());

			// 获取到前12位
			String barCode = jbarCode.substring(0, len - 1);

			// 获取到校验位
			String code = jbarCode.substring(len - 1, len);
			String checkCode = jbarcode13.calcCheckSum(barCode);

			if (!code.equals(checkCode)) {
				return "EN-13 条形码最后一位校验码 不对,应该是: " + checkCode;
			}

			/*
			 * 最重要的是这里的设置,如果明白了这里的设置就没有问题 如果是默认设置, 那么设置就是生成一般的条形码 如果不是默认
			 * 设置,那么就可以根据自己需要设置
			 */

			// 尺寸,面积,大小
			jbarcode13.setXDimension(Double.valueOf(0.8).doubleValue());
			// 条形码高度
			jbarcode13.setBarHeight(Double.valueOf(30).doubleValue());
			// 宽度率
			jbarcode13.setWideRatio(Double.valueOf(20).doubleValue());
			// 是否校验最后一位,默认是false
			jbarcode13.setShowCheckDigit(true);

			// 生成二维码
			bi = jbarcode13.createBarcode(barCode);

			// 定义图片名称
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
			String imgName = sdf.format(new Date()) + "_" + jbarCode;

			// 保存二维码图片

			FileOutputStream fileOutputStream = null;
			String imgPath = savePath + imgName + "." + imgFormat;
			try {
				try {
					savePath = URLDecoder.decode(savePath, "UTF-8");
				} catch (UnsupportedEncodingException uee) {
					uee.printStackTrace();
					savePath = "C://barcode//images//";
				}
				File dirFile = new File(savePath);

				if (!dirFile.exists()) {
					dirFile.mkdirs();
				}

				fileOutputStream = new FileOutputStream(imgPath);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			ImageUtil.encodeAndWrite(bi, imgFormat, fileOutputStream, 96, 96);
			fileOutputStream.close();

			// 返回路径
			return imgPath;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 生成商品条形码
	 *
	 * @param filePath
	 *            商品条形码图片存放路径:C://barcode//images//
	 *
	 * @param barCode
	 *            商品条形码:11位
	 * @param imgFormat
	 *            图片格式
	 * 
	 * @return 图片存放路径+图片名称+图片文件类型
	 */
	public static String createBarCode11(String savePath, String jbarCode, String imgFormat) {

		// 校验全部省略……
		// if(StringUtils.isNotEmpty(savePath)){
		//

		// return null;
		// }
		// if(StringUtils.isNotEmpty(jbarCode)){
		// return null;
		// }
		// if(StringUtils.isNotEmpty

		// (imgFormat)){
		// return null;
		// }
		// if( jbarCode.length()!=13){
		// return null;
		// }

		try {

			BufferedImage bi = null;

			int len = jbarCode.length();

			// 实例化JBarcode
			// 这里三个参数,必要填写
			JBarcode jbarcode11 = new JBarcode(Code11Encoder.getInstance(), WidthCodedPainter.getInstance(),
					EAN13TextPainter.getInstance());

			// 获取到前11位
			String barCode = jbarCode.substring(0, len - 1);


			/*
			 * 最重要的是这里的设置,如果明白了这里的设置就没有问题 如果是默认设置, 那么设置就是生成一般的条形码 如果不是默认
			 * 设置,那么就可以根据自己需要设置
			 */

			// 尺寸,面积,大小
			jbarcode11.setXDimension(Double.valueOf(0.5).doubleValue());
			// 条形码高度
			jbarcode11.setBarHeight(Double.valueOf(20).doubleValue());
			// 宽度率
			jbarcode11.setWideRatio(Double.valueOf(30).doubleValue());
			// 是否校验最后一位,默认是false
			jbarcode11.setShowCheckDigit(true);

			// 生成二维码
			bi = jbarcode11.createBarcode(barCode);

			// 定义图片名称
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
			String imgName = sdf.format(new Date()) + "_" + jbarCode;

			// 保存二维码图片

			FileOutputStream fileOutputStream = null;
			String imgPath = savePath + imgName + "." + imgFormat;
			try {
				try {
					savePath = URLDecoder.decode(savePath, "UTF-8");
				} catch (UnsupportedEncodingException uee) {
					uee.printStackTrace();
					savePath = "D://barcode//images//";
				}
				File dirFile = new File(savePath);

				if (!dirFile.exists()) {
					dirFile.mkdirs();
				}

				fileOutputStream = new FileOutputStream(imgPath);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			ImageUtil.encodeAndWrite(bi, imgFormat, fileOutputStream, 96, 96);
			fileOutputStream.close();

			// 返回路径
			return imgPath;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @param args
	 * @throws InvalidAtributeException
	 */
	public static void main(String[] args) throws InvalidAtributeException {

		//String path = TestBarcode.createBarCode("D://barcode//", "6937748304340", ImageUtil.JPEG);

		String path = TestBarcode.createBarCode11("D://barcode//", "99005050002", ImageUtil.JPEG);

		System.out.println(path);

	}

}
(二)成果展示


(三)页面展示

生成图片后,用Base64编码后得到字符串,假如为:"123xyz"

<img src="data:image/png;base64,123xyz"/>

获取图片字符串代码如下(网上资源):

package com.nicole.test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code11Encoder;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.encode.EAN13Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WidthCodedPainter;

import sun.misc.BASE64Encoder;  
   
public class BarcodeUtil {  
      
    /**  
     * 11条形码  
     *  
     * @param strBarCode  
     *            商品条形码:11位  
     * @param dimension  
     *            商品条形码:尺寸  
     * @param barheight  
     *            商品条形码:高度  
     * @return 图片(Base64编码)  
     */  
      public static String generateBarCode11(String strBarCode,String dimension,String barheight) {  
              
       
            try {  
                ByteArrayOutputStream outputStream = null;  
                BufferedImage bi = null;  
                int len = strBarCode.length();  
                JBarcode productBarcode = new JBarcode(Code11Encoder.getInstance(),  
                        WidthCodedPainter.getInstance(),  
                        EAN13TextPainter.getInstance());  
       
                // 尺寸,面积,大小 密集程度  
                productBarcode.setXDimension(Double.valueOf(dimension).doubleValue());  
                // 高度 10.0 = 1cm 默认1.5cm  
                productBarcode.setBarHeight(Double.valueOf(barheight).doubleValue());  
                // 宽度  
                productBarcode.setWideRatio(Double.valueOf(30).doubleValue());  
//                  是否显示字体  
                productBarcode.setShowText(true);  
//                 显示字体样式  
                productBarcode.setTextPainter(BaseLineTextPainter.getInstance());   
       
                // 生成二维码  
                bi = productBarcode.createBarcode(strBarCode);  
                  
                outputStream = new ByteArrayOutputStream();  
                ImageIO.write(bi, "jpg", outputStream);  
                BASE64Encoder encoder = new BASE64Encoder();  
//            System.err.println(encoder.encode(outputStream.toByteArray()));  
  
                return encoder.encode(outputStream.toByteArray());  
            } catch (Exception e) {  
                e.printStackTrace();  
                return "encodeError";  
            }  
        }  
    /**  
     * @param args  
     * @throws InvalidAtributeException  
     */  
    public static void main(String[] args) throws InvalidAtributeException {  
    	String encode = BarcodeUtil.generateBarCode11("99005050002","0.5","20");  
        System.out.println(encode);
    }  
   
}  



copy控制台输出的图片编码到img标签中即可


猜你喜欢

转载自blog.csdn.net/ththcc/article/details/80081098