java 后臺將base64字符串保存為圖片的方法
更新時間:2017年09月22日 10:25:48 作者:Mr_伍先生
本篇文章主要介紹了java 后臺將base64字符串保存為圖片的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了java 后臺將base64字符串保存為圖片的方法,分享給大家,具體如下:
直接上代碼:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Test
{
public static void main(String[] args)
{
String strImg = GetImageStr();
System.out.println(strImg);
GenerateImage(strImg);
}
//圖片轉化成base64字符串
public static String GetImageStr()
{//將圖片文件轉化為字節(jié)數(shù)組字符串,并對其進行Base64編碼處理
String imgFile = "D:\\tupian\\a.jpg";//待處理的圖片
InputStream in = null;
byte[] data = null;
//讀取圖片字節(jié)數(shù)組
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//對字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64編碼過的字節(jié)數(shù)組字符串
}
//base64字符串轉化成圖片
public static boolean GenerateImage(String imgStr)
{ //對字節(jié)數(shù)組字符串進行Base64解碼并生成圖片
if (imgStr == null) //圖像數(shù)據(jù)為空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//調整異常數(shù)據(jù)
b[i]+=256;
}
}
//生成jpeg圖片
String imgFilePath = "D:\\tupian\\new.jpg";//新生成的圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
基于@RestControllerAdvice與@ControllerAdvice的區(qū)別說明
這篇文章主要介紹了@RestControllerAdvice與@ControllerAdvice的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
Spring Boot Web 靜態(tài)文件緩存處理的方法
本篇文章主要介紹了Spring Boot Web 靜態(tài)文件緩存處理的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
Java synchronized關鍵字和Lock接口實現(xiàn)原理
這篇文章主要介紹了Java synchronized關鍵字和Lock接口實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
SpringBoot2.x實現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴
這篇文章主要介紹了SpringBoot2.x實現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02

