java这边的话生成二维码有很多开发的jar包如zxing,qrcode.q前者是谷歌开发的后者则是小日本开发的,这里的话我使用zxing的开发包来弄
先下载zxing开发包,这里用到的只是core那个jar包(我用的是core-3.1.0.jar)
github: https://github.com/zxing/zxing/wiki/Getting-Started-Developing,
当然你也可以从maven仓库下载jar包: http://central.maven.org/maven2/com/google/zxing/core/
实现类:
public class ZxingCode
{
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private ZxingCode()
{
}
public static BufferedImage getQRCodeImage(String contents, int width, int height)
{
BufferedImage image = null;
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
if(contents == null || width<=0 || height<=0){
return null;
}
try
{
BitMatrix matrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
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);
}
}
}
catch (WriterException e)
{
e.printStackTrace();
}
return image;
}
public static void writeToFile(String contents, int width, int height,
File file, String format) throws IOException
{
BufferedImage image = getQRCodeImage(contents, width, height);
if (!ImageIO.write(image, format, file))
{
throw new IOException("Could not write an image of format "
+ format + " to " + file);
}
}
public static void writeToStream(String contents, int width, int height,
String format, OutputStream stream) throws IOException
{
BufferedImage image = getQRCodeImage(contents, width, height);
if (!ImageIO.write(image, format, stream))
{
throw new IOException("Could not write an image of format "
+ format);
}
}
}
controller层获取操作:
@RequestMapping(value="/get_qrcode.jhtml", method=RequestMethod.GET)
public void getQRCode(HttpServletRequest request ,HttpServletResponse response){
String content = this.getParameter("content");
/*
//例子一
BufferedImage image = ZxingCode.getQRCodeImage(content, 230, 230);
try
{
ServletOutputStream stream = response.getOutputStream();
if(image != null){
ImageIO.write(image, "png", stream);
}
stream.flush();
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}*/
try
{
/*
//例子二
File outputFile = new File("E:/mynew.jpeg");
ZxingCode.writeToFile(content, 300, 300, outputFile, "png");
*/
//例子三
ZxingCode.writeToStream(content, 230, 230, "jpg", response.getOutputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
}
maven依赖:
com.google.zxing
core
3.1.0
前台页面:
X分享到微信朋友圈