遠程服務器圖片轉換為Base64編碼
/**
* 服務器圖片轉換base64 path:服務器圖片路徑 返回 base64編碼(String 類型)
* @param path
* @return
*/
public static String imgToBase64(String path){
byte[] data = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try{
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
in = connection.getInputStream();
out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len =in.read(b)) != -1){
out.write(b,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(in != null ){
in.close();
}
}catch (IOException e){
e.getStackTrace();
}
}
System.out.println("轉換后的圖片大小:"+out.toByteArray().length/1024);
BASE64Encoder base = new BASE64Encoder();
return base.encode(out.toByteArray());
}
Base64編碼轉換為圖片輸出
/**
* base64 編碼轉換為圖片, base:base64編碼 字符串 path:轉換完之后的圖片存儲地址
* @param base
* @param path
* @return
*/
public static boolean base64ToImg(String base,String path){
if(StringUtil.isBlank(base)){
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try{
byte[] bytes = decoder.decodeBuffer(base);
for(int i = 0;i < bytes.length; ++i){
if(bytes[i] < 0){
bytes[i]+=256;
}
}
out = new FileOutputStream(path);
out.write(bytes);
out.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
}catch (IOException e){
e.getStackTrace();
}
}
return true;
}