bash64<<------>>>图片

本文介绍如何将图片转换为Base64格式并存入数据库,同时提供了将Base64数据还原为图片的方法。文中详细解释了编码和解码过程,并展示了如何在前后端实现这些功能。

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

接收前端传过来的图片,将图片转为bash64格式存放到数据库中,能够在任何一台电脑上显示你所存放的图片

Bash64格式转png、jpg格式图片

1、首先编写工具类

    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();

    /**
     * 将图片转化为Bash64位格式
     * @param imageAddress 图片地址
     * @param imageFormat 图片格式(jpg/png/...)
     * @return
     */
    public static String getImageBase(String imageAddress, String imageFormat) {
        File file = new File(imageAddress);
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, imageFormat, byteStream);
            byte[] bytes = byteStream.toByteArray();
            return encoder.encodeBuffer(bytes).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将Bash64位格式转为图片,存放在【filePath】下
     * @param base64String bash64位格式数据
     * @param filePath 文件存放地址
     * @param fileFromat 文件格式
     */
    public static void base64StringToImage (String base64String, String filePath, String fileFromat) {
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File f1 = new File(filePath);
            ImageIO.write(bi1, fileFromat, f1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、进入实战
2.1 数据库部分
在这里插入图片描述
用的longtext来保存的bash64位数据
2.2 实体类部分

	private String picture;
2.3 后台部分
    @GetMapping("/getImageBase")
    public void getImageBase() {
        BASE64Encoder encoder = new BASE64Encoder();
        File file = new File("C:\\Users\\12425\\Desktop\\demo.jpg");
        try {
            BufferedImage bi = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();
            String data = encoder.encodeBuffer(bytes).trim();
            int i = userMapper.updateBash64(data);  // 只是一个简单的sql,将数据修到了数据库中
            System.out.println(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
2.4 前台部分

首先查询到picture这个数据,在这个长字符串前面加上 data:image/jpg;base64, 即可转为图片,在前台页面显示!

      <el-image v-if="picture" :src="getUrl(picture)" class="avatar"></el-image>
    getUrl (picture) {
      var photo = "data:image/jpg;base64,"+picture.replace(/[]/g,"")
      return photo
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值