生成二维码png图片
1.导入jar包
Qrcode.jar
2.执行代码
import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; public class Test { public static void main(String[] args) { new Test().createImg("http://www.baidu.com/baidu?wd=asdasdasfsafassdasdsadasdas&tn=monline_4_dg", "D:\\logs\\", "QRCode"); new Test().createImg("http://www.shanshanbox.com", "D:\\logs\\", "QRCode2"); } public void createImg(String url, String folder, String fileName){ int codeWidth; int unitWidth = 50; Qrcode qrcode=new Qrcode(); qrcode.setQrcodeErrorCorrect('M');/* L','M','Q','H' */ qrcode.setQrcodeEncodeMode('B');/* "N","A" or other */ qrcode.setQrcodeVersion(0);/* 0-20 */ String testString = url; byte[] buff = null; try { buff = testString.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(buff.length); boolean[][] bRect = qrcode.calQrcode(buff); codeWidth = bRect.length * unitWidth; BufferedImage bi = new BufferedImage(codeWidth, codeWidth, BufferedImage.TYPE_INT_RGB); // createGraphics Graphics2D g = bi.createGraphics(); // set background g.setBackground(Color.WHITE); g.clearRect(0, 0, codeWidth, codeWidth); g.setColor(Color.BLACK); if (buff.length>0 && buff.length <123){ for (int i=0;i<bRect.length;i++){ for (int j=0;j<bRect.length;j++){ if (bRect[j][i]) { g.fillRect(j*unitWidth, i*unitWidth, unitWidth, unitWidth); } } } } g.dispose(); bi.flush(); String FilePath=folder + fileName + ".png"; File f = new File(FilePath); try { ImageIO.write(bi, "png", f); } catch (IOException e) { e.printStackTrace(); } } }