这篇文章主要介绍了Java处理图片实现base64编码转换的示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
注意事项
一般插件返回的base64编码的字符串都是有一个前缀的。"data:image/jpeg;base64," 解码之前这个得去掉。
Code
MainTest
/**
* 示例
* @throws UnsupportedEncodingException
* @throws FileNotFoundException
*/
@SuppressWarnings("resource")
public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
String strImg = getImageStr("Z:\\水印\\2.bmp");
System.out.println(strImg);
File file = new File("z://1.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
try {
osw.write(strImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//generateImage(strImg, "Z:\\水印\\444.bmp");
}
加密:
**
* @Description: 根据图片地址转换为base64编码字符串
* @Author:
* @CreateTime:
* @return
*/
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(data);
}
解密:
/**
* @Description: 将base64编码字符串转换为图片
* @Author:
* @CreateTime:
* @param imgStr base64编码字符串
* @param path 图片路径-具体到文件
* @return
*/
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null)
return false;
// 解密
try {
Decoder decoder = Base64.getDecoder();
byte[] b = decoder.decode(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (IOException e) {
return false;
}
}
Java主要应用于:1. web开发;2. Android开发;3. 客户端开发;4. 网页开发;5. 企业级应用开发;6. Java大数据开发;7.游戏开发等。
感谢你能够认真阅读完这篇文章,希望小编分享的“Java处理图片实现base64编码转换的示例”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。