Base64实现传输图片

1. Base64简介 

Base64是一种基于64个可打印字符来表示二进制数据的表示方法。通常用于在URL、Cookie和邮件等场景中,将二进制数据转换为字符串形式进行传输。

代码实现

public class ImageUtils {
    /**
     * 得到图片的Base64编码
     * @param imagePath 图片路径
     * @return 64编码字符串
     */
    public static String imageToBase64(String imagePath) {

        final Pattern BASE64_PATTERN=Pattern.compile(
                "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$");
        //如果已经是64编码直接返回
        if( BASE64_PATTERN.matcher(imagePath).matches()){
            return imagePath;
        }else {
            StringBuilder base64Image = new StringBuilder();
            File file = new File(imagePath);
            try (FileInputStream imageInFile = new FileInputStream(file)) {
                byte[] imageData = new byte[(int) file.length()];
                int bytesRead;
                while ((bytesRead = imageInFile.read(imageData)) != -1) {
                    // 每次读取到的实际字节数组长度为 bytesRead
                    byte[] partialData = new byte[bytesRead];
                    System.arraycopy(imageData, 0, partialData, 0, bytesRead);
                    base64Image.append(Base64.getEncoder().encodeToString(partialData));
                }
            } catch (IOException e) {
                System.out.println("Error: " + e.getMessage());
            }
            return base64Image.toString();
        }
    }

    /**
     * 将前端传来的ase64编码解码
     * @param imageBase64 图片的Base64编码
     * @param path 存放的路径
     */
    public static void imageSetBase64(String imageBase64, String path){

        String[] base64Parts = imageBase64.split(",");
        String base64Data = base64Parts[1]; // 实际的Base64编码数据部分

        byte[] imageBytes = Base64.getDecoder().decode(base64Data);

        // 现在imageBytes中存储了解码后的图像数据,可以进行存储或处理
        // 下面是示例存储到文件系统的方法
        try (FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

3分人生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值