编码
/**
* 在线图片Base64编码
* @param link 在线图片请求地址
* @return
* @throws IOException
*/
public static String toBase64(String link) {
byte[] data = null;
InputStream inputStream = null;
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
inputStream = conn.getInputStream();
//这里为分界上面代码是拿到网络图片,下面代码是编码
data = new byte[inputStream.available()];
if (inputStream != null){
inputStream.read(data);
}
if (inputStream != null){
inputStream.close();
}
}catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
解码
/**
* 文件Base64解码Java示例代码
*
* @param str 需要解码的字符
* @param filePath 生成文件的路径
* @return
*/
public static boolean decodeStrToFile(String str, String filePath) {
if (str == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(str);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
OutputStream out = new FileOutputStream(filePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}