/**
* @author 王一宁
* @date 2020/2/24 8:54
*/
public class Base64Utils {
//本地图片转换成base64
public static String ImageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
//System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
return encoder.encode(Objects.requireNonNull(data));
}
//网络图片转换成base64
public static void NetImageToBase64(String netImagePath) {
final ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(netImagePath);
final byte[] by = new byte[1024];
// 创建链接
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
String strNetImageToBase64 = encoder.encode(data.toByteArray());
System.out.println("网络图片转换Base64:" + strNetImageToBase64);
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
//base64转换成图片
public static String decryptByBase64(String base64, String filePath) throws Exception{
if (base64 == null && filePath == null) {
return "生成文件失败,请给出相应的数据。";
}
try {
Files.write(Paths.get(filePath),Base64.decode(base64), StandardOpenOption.CREATE);
} catch (IOException e) {
throw e;
}
return "指定路径下生成文件成功!";
}
}
评论