標籤:springmvc mysql mybatis oracle sqlserver
說下背景,項目中遇到前端js擷取圖片發生跨域的問題,伺服器端又不支援匿名訪問,只能通過伺服器擷取圖片base64碼進行展示。代碼如下:下載
Java代碼 650) this.width=650;" class="star" src="http://songfeng-123.iteye.com/images/icon_star.png" alt="收藏代碼" style="border:0px;" />
/**
* 遠程讀取image轉換為Base64字串
* @param imgUrl
* @return
*/
private String Image2Base64(String imgUrl) {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try{
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入資料流從buffer裡把資料讀取出來
while( (len=is.read(buffer)) != -1 ){
//用輸出資料流往buffer裡寫入資料,中間參數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
// 對位元組數組Base64編碼
return new BASE64Encoder().encode(outStream.toByteArray());
}catch (Exception e) {
e.printStackTrace();
} 下載
finally{
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outStream != null)
{
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpUrl != null)
{
httpUrl.disconnect();
}
}
return imgUrl;
}
java遠程擷取圖片產生base64串