使用hutool工具包来生成二维码,得到BufferedImage ,再将其转为base64
// 二维码生成工具类
public class QrCodeUtils {
/**
* 文件BufferedImage类型转BASE64
*
* @param bufferedImage
* @return
*/
public static String imageToBase64(BufferedImage bufferedImage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
try {
ImageIO.write(bufferedImage, "png", baos);//写入流中
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = baos.toByteArray();//转换成字节
BASE64Encoder encoder = new BASE64Encoder();
String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
return "data:image/png;base64," + png_base64;
}
/**
* 文件File类型转BASE64
*
* @param file
* @return
*/
public static String fileToBase64(File file) {
return "data:image/png;base64," + Base64.encodeBase64String(fileToByte(file));
}
/**
* 文件File类型转byte[]
*
* @param file
* @return
*/
private static byte[] fileToByte(File file) {
byte[] fileBytes = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
fileBytes = new byte[(int) file.length()];
fis.read(fileBytes);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileBytes;
}
public static void main(String[] args) {
String result=imageToBase64(QrCodeUtil.generate("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7f64c851e8a24dcb&redirect_uri=https://yxyshop-uat.hnyxtour.com/tdos/system/notify/submit/15/wx7f64c851e8a24dcb/3f6be86d61cfbc74472fa04426b3004d.do&response_type=code&scope=snsapi_userinfo&#wechat_redirect", 300, 300));
System.out.println(result);
}
}
记录一些开发时遇到的工具