图片或者视频转二进制流进行Base64加密

一:读取图片或者视频,转换二进制流,进行Base64加密 

    @PostMapping("/base64Encoder")
    public StringBuilder changeImageTobase64(String imageFilePath) {
        InputStream in = null;
        byte[] imageByte = null;
        if (imageFilePath == null || "".equals(imageFilePath)) {
            //默认文件地址,可以是图片或者是地址
//            imageFile="C:/Users/zbh19/Pictures/Saved Pictures/艾玛沃特森.jpeg";
            imageFilePath="C:/Users/zbh19/Pictures/Saved Pictures/123.mp4";
        }
        try {
            //读取文件
            in = new FileInputStream(imageFilePath);
            int size = in.available();
            imageByte = new byte[size];
            //从输入流中将数据读入一个 imageByte字节 数组中。
            in.read(imageByte);
            //关闭此文件输入流并释放与此流有关的所有系统资源。
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果是视频,转成二进制或者是转成Base64加密后,字符长度会非常长
        //举例:1.1M的视频大概是将近120w字符,所以String类型肯定不行,String是65535(127kb)超出会报错
        //而且,String会占用常量池,常量池的内存占用,一般很难被清理掉,
        //这么个长的字符串很容易造成OOM
        //StringBuilder 长度是 int 的最大值 2的32次幂 ,21亿 个字符
        StringBuilder stringBuilder = new StringBuilder();
        // 对字节数组转换成Base64字符串
//        String base64String = Base64.getEncoder().encodeToString(imageByte);
        stringBuilder.append(Base64.getEncoder().encodeToString(imageByte));
        changeBase64ToImage(stringBuilder);
        return null;
    }

 二:将base64格式的字符串转换成二进制流,并转换成对应的文件进行存储

/**
     * 将base64格式的字符串转换成二进制流进行存储
     */
    @PostMapping("/base64Decoder")
    public boolean changeBase64ToImage(StringBuilder base64String) {
        //base64格式字符串为空,返回false
        if (base64String == null) {
            return false;
        }
        try {
            //对Base64字符串进行解码,转化为二进制流
            byte[] imageByte = Base64.getDecoder().decode(base64String.toString());
            //生成图片路径和文件名
            String pathString = "D:/test/" + UUID.fastUUID() + ".mp4";
            OutputStream out = new FileOutputStream(pathString);
            out.write(imageByte);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/zbh1957282580/article/details/126154362