java生成二维码到文件,java生成二维码转成BASE64
如题,利用java和第三方库,把指定的字符串生成二维码,并且把二维码保存成图片,转换成BASE64格式。
需要的jar文件:
package com.xueyoucto.xueyou;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;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import sun.misc.BASE64Encoder;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;/*** Hello world!*/
public class App {public static void main(String[] args) throws IOException {System.out.println("hello world");String text = "999666111222";int width = 300;int height = 300;String format = "png";Hashtable hints = new Hashtable();hints.put(EncodeHintType.CHARACTER_SET, "utf-8");BitMatrix bitMatrix = null;try {bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);} catch (WriterException e) {e.printStackTrace();}//直接写入文件File outputFile = new File("d:/new.png");MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);//通过流写入文件,不需要flush()OutputStream os1 = new FileOutputStream("d:/new2.png");MatrixToImageWriter.writeToStream(bitMatrix, format, os1);BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。ImageIO.write(image, format, os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。byte b[] = os.toByteArray();//从流中获取数据数组。String str = new BASE64Encoder().encode(b);System.out.println(str);}
}
运行结果:
图片:
把这个图片放在这个网址中验证一下图片在线转换base64:
结果发现和上面输出的相同。
当然,是不包含头部的。
如果没有jar包之类的,直接点我下载整个工程,不要你的积分噢!