import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Hashtable; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; 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; @Controller @RequestMapping("barcode") public class BarcodeController { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; @RequestMapping("/getBarcode") public void generateBarcode(HttpServletRequest req,HttpServletResponse resp,HttpSession session) throws WriterException, IOException { /***************下面參數能夠放在web.xml文件中配置,經過this.getParameter(String paramName)調用獲取;或放入配置文件中***************/ String text = "http://www.baidu.com"; int width = 300; int height = 300; String format = "gif"; //二維碼圖片格式 Hashtable<EncodeHintType,Object> hints = new Hashtable<EncodeHintType,Object>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints); BufferedImage image = toBufferedImage(bitMatrix); ServletOutputStream str = resp.getOutputStream(); ImageIO.write(image, format, str); str.close(); } public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE); } } return image; } }