网络图片转base64,图片与base64互转
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
@Component
public class ImageBase64Utils {
public static void main(String[] args) throws Exception {
String string = "https://img-home.csdnimg.cn/images/20201124032511.png";
String ste = ImageToBase64ByOnline(string);
System.out.println(ste);
}
public static String ImageToBase64ByOnline(String imgURL) {
try {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
URL url = new URL(imgURL);
byte[] by = new byte[1024];
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
is.close();
} catch (IOException e) {
log.error("ImageToBase64ByOnline find IOException:", e);
}
return Base64Utils.encodeToString(data.toByteArray());
} catch (Exception e) {
log.error("ImageToBase64ByOnline find Exception:", e);
}
return null;
}
public static boolean Base64ToImage(String imgStr, String imgFilePath) {
if (StringUtils.isBlank(imgStr)) {
return false;
}
try {
byte[] b = Base64Utils.decodeFromString(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
log.error("Base64ToImage find Exception:", e);
return false;
}
}
public static String ImageToBase64ByLocal(String imgFile) {
try {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
log.error("ImageToBase64ByLocal find IOException:", e);
}
return Base64Utils.encodeToString(data);
} catch (Exception e) {
log.error("ImageToBase64ByLocal find Exception:", e);
}
return null;
}
}