java将图片转byte存入数据库_Java将byte[]转图片存储到本地的案例
Java中,將字節(jié)數(shù)組轉(zhuǎn)成圖片的有很多種方式,今天在這里記錄其中一種,方便以后查詢,也可以提供給沒有接觸的童鞋做一個(gè)參考。
首先是將圖片轉(zhuǎn)成字節(jié)數(shù)組
import sun.misc.BASE64Encoder;
import java.io.*;
// 傳入圖片路徑,獲取圖片
FileInputStream fis = new FileInputStream("/Users/curry/error.png");
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
bos.write(buff, 0, len);
}
// 得到圖片的字節(jié)數(shù)組
byte[] result = bos.toByteArray();
// 將數(shù)組轉(zhuǎn)為字符串
BASE64Encoder encoder = new BASE64Encoder();
String str = encoder.encode(result).trim();
將數(shù)組轉(zhuǎn)為圖片
import sun.misc.BASE64Decoder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgbyte = decoder.decodeBuffer("剛剛將字節(jié)數(shù)組轉(zhuǎn)成的字符串");
OutputStream os = new FileOutputStream("/Users/curry/text.png");
os.write(imgbyte, 0, imgbyte.length);
os.flush();
os.close();
補(bǔ)充知識:java將圖片轉(zhuǎn)化為base64和base64轉(zhuǎn)化為圖片編碼并保存在本地
我就廢話不多說了,大家還是直接看代碼吧~
public class Base64Convert {
/**
* @Description: 圖片轉(zhuǎn)化成base64字符串
* @param: path
* @Return:
*/
public static String GetImageStr(String path)
{
//將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對其進(jìn)行Base64編碼處理
//待處理的圖片
String imgFile = path;
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();
//返回Base64編碼過的字節(jié)數(shù)組字符串
return encoder.encode(data);
}
/**
* @Description: base64字符串轉(zhuǎn)化成圖片
* @param: imgStr
* @Return:
*/
public static boolean GenerateImage(String imgStr,String photoname)
{
//對字節(jié)數(shù)組字符串進(jìn)行Base64解碼并生成圖片
//圖像數(shù)據(jù)為空
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i
{
if(b[i]<0)
{
//調(diào)整異常數(shù)據(jù)
b[i]+=256;
}
}
//生成jpeg圖片
String imagePath= Config.getUploadPhysicalPath();
//System.currentTimeMillis()
//新生成的圖片
String imgFilePath = imagePath+photoname;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
以上這篇Java將byte[]轉(zhuǎn)圖片存儲(chǔ)到本地的案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持自學(xué)編程網(wǎng)。
總結(jié)
以上是生活随笔為你收集整理的java将图片转byte存入数据库_Java将byte[]转图片存储到本地的案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机 电工学简明教程,电工学简明教程复
- 下一篇: css居中的几种方法_CSS布局中的水平