將圖片轉成字節數組:
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);
}
// 得到圖片的字節數組
byte[] result = bos.toByteArray();
// 將數組轉為字符串
BASE64Encoder encoder = new BASE64Encoder();
String str = encoder.encode(result).trim();
將數組轉為圖片:
import sun.misc.BASE64Decoder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgbyte = decoder.decodeBuffer("剛剛將字節數組轉成的字符串");
OutputStream os = new FileOutputStream("/Users/curry/text.png");
os.write(imgbyte, 0, imgbyte.length);
os.flush();
os.close();
補充:java將圖片轉化為base64和base64轉化為圖片編碼並保存在本地
public class Base64Convert {
/**
* @Description: 圖片轉化成base64字符串
* @param: path
* @Return:
*/
public static String GetImageStr(String path)
{
//將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理
//待處理的圖片
String imgFile = path;
InputStream in = null;
byte[] data = null;
//讀取圖片字節數組
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
//返回Base64編碼過的字節數組字符串
return encoder.encode(data);
}
/**
* @Description: base64字符串轉化成圖片
* @param: imgStr
* @Return:
*/
public static boolean GenerateImage(String imgStr,String photoname)
{
//對字節數組字符串進行Base64解碼並生成圖片
//圖像數據為空
if (imgStr == null)
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)
{
//調整異常數據
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中,將字節數組轉成圖片的有很多種方式,在這里記錄其中一種
利用js改變img標簽中的src
<!DOCTYPE html>
<html class=" ">
<head>
<meta charset="utf-8">
<title>圖片</title>
</head>
<body class="">
<img id="pic" />
</body>
<script type="text/javascript">
var url = "data:image/png;base64,"; <!-- "data:image/png;charset=utf-8;base64," -->
var i = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMzTjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC";
setInterval(showPicture,100) <!-- setInterval(函數,調用時間間隔) 方法可按照指定的周期(以毫秒計)來調用函數或計算表達式。 -->
function showPicture(){
document.getElementById("pic").src = url+ i;
}
</script>
</html>
利用ajax前后端交互,再加上定時器不停的刷新,前端界面即可實現動態刷新圖片的效果
把圖像二進制流文件的內容直接寫在了HTML 文件中,這樣做的好處是,節省了一個HTTP 請求。壞處就是瀏覽器不會緩存這種圖像。大家可以根據實際情況進行自由取舍。
