import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
@Slf4j
public class Base64Util {
private static final String BASE64HEAD = "data:image/";
private static final String BASE64TYPE = ";base64,";
private static final Base64.Encoder encoder = Base64.getEncoder();
private static final Base64.Decoder decoder = Base64.getDecoder();
public static String image2Base64(String imgUrl) {
String suffix = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
if (!"jpg".equalsIgnoreCase(suffix) && !"png".equalsIgnoreCase(suffix)) {
log.error("图片格式支持jpg,png。");
return "";
}
URL url;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
url = new URL(imgUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(100000);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = inputStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
baos.write(buffer, 0, len);
}
// 对字节数组Base64编码
imgUrl = encoder.encodeToString(baos.toByteArray());
return BASE64HEAD.concat(suffix).concat(BASE64TYPE).concat(imgUrl);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return "";
}
public static boolean checkImageBase64(String imgUrl) {
boolean flag = true;
ByteArrayInputStream byteArrayInputStream = null;
try {
byte[] byteArray = decoder.decode(imgUrl);
byteArrayInputStream = new ByteArrayInputStream(byteArray);
BufferedImage bufImg = ImageIO.read(byteArrayInputStream);
if (bufImg == null) {
flag = false;
log.error("Base64字符串非图片。");
}
} catch (IOException e) {
flag = false;
log.error(e.getMessage());
} finally {
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return flag;
}
}