博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BASE64图片转字符串
阅读量:7007 次
发布时间:2019-06-28

本文共 1903 字,大约阅读时间需要 6 分钟。

Java代码图片字符串互转

/**     * 将base64字符串转成图片     * TODO     * @param imgStr base64图片字符串     * @param path 目标输出路径     * @return     */    public static boolean base64StrToImage(String imgStr, String path) {        if (imgStr == null)            return false;        BASE64Decoder decoder = new BASE64Decoder();        try {            // 解密base64图片字符串            byte[] b = decoder.decodeBuffer(imgStr);            // 处理数据,把负的byte字节数据改为正的,作用未知            for (int i = 0; i < b.length; ++i) {                if (b[i] < 0) {                    b[i] += 256;                }            }            File tempFile = new File(path);            //文件夹不存在则自动创建            if (!tempFile.getParentFile().exists()) {                tempFile.getParentFile().mkdirs();            }            OutputStream out = new FileOutputStream(tempFile);            out.write(b);            out.flush();            out.close();            return true;        } catch (Exception e) {            return false;        }    }     /* 图片转base64字符串      * @param imgFile 图片路径      * @return base64字符串格式的图片      */     public static String imageToBase64Str(String imgFile) {       InputStream inputStream = null;       byte[] data = null;       try {         inputStream = new FileInputStream(imgFile);         data = new byte[inputStream.available()];  //根据文件流字节大小初始化data字节数组大小         inputStream.read(data);  //将流读入data         inputStream.close();  //关闭流       } catch (IOException e) {         e.printStackTrace();       }       //将图片数组加密       BASE64Encoder encoder = new BASE64Encoder();       return encoder.encode(data);     }        public static void main(String[] args) {        String base64Str = imageToBase64Str("D:/20190307/2.jpg");        System.out.println(base64Str);                 boolean b = base64StrToImage(base64Str, "D:/3.jpg");        System.out.println(b);    }

 

转载于:https://www.cnblogs.com/aeolian/p/10494895.html

你可能感兴趣的文章
linux cut命令
查看>>
(转)linux各文件夹的作用
查看>>
对啊英语音标---四、双元音常见的字母发音组合有哪些
查看>>
win10如何一键开启关闭windows Defender(亲测有效)
查看>>
仿联想商城laravel实战---2、后端页面搭建(验证码如何在页面中使用)
查看>>
js进阶 12-7 如何知道你是从哪个元素移动到当前元素与事件调用时如何添加额外数据...
查看>>
day7 socket网络编程
查看>>
《大道至简》阅读笔记1
查看>>
Python 进阶_OOP 面向对象编程_类和继承
查看>>
C#之自定义的implicit和explicit转换
查看>>
multipath 多路冗余
查看>>
【学习笔记】非递归实现先后根遍历二叉树
查看>>
你看那个人他像一条狗
查看>>
Delegate。。
查看>>
Throwing cards away I
查看>>
组合数末尾的零
查看>>
flex 特性
查看>>
SpringCloud2.0 Hystrix Dashboard 断路器指标看板 基础教程(八)
查看>>
全国DNS服务器IP地址【电信、网通、铁通】
查看>>
【LIbreOJ】#6256. 「CodePlus 2017 12 月赛」可做题1
查看>>