使用hutool工具生成图片二维码并且转换为base64

这段代码展示了如何在Java中将BufferedImage类型的图片和File类型的文件转换为BASE64编码。首先,将图片写入到ByteArrayOutputStream,然后转换为字节数组并使用BASE64Encoder编码。对于File,直接将其转换为字节数组再进行BASE64编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   
	/**
	 * 文件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;
    }


  String result=imageToBase64(QrCodeUtil.generate("https://hutool.cn/", 300, 300))
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值