import org.apache.commons.lang.StringUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public final class ImageUtil {
public static final String CACHE_KEY_PREFIX = "com.efe.images.cache-";
private static final Integer MAX_WIDTH = 5000;
private static final Integer MAX_HEIGHT = 5000;
private static final Integer MIN_WIDTH = 330;
private static final Integer MIN_HEIGHT = 330;
public static String getSuffix(String url){
if(url == null || "".equals(url.trim())){
return null;
}
if(url.contains("?")){
url = url.substring(0,url.lastIndexOf("?"));
}
return url.substring(url.lastIndexOf("."), url.length());
}
public static boolean isJPGSuffix(String url){
String suffix = getSuffix(url);
return suffix != null && (suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".jpeg"));
}
private static String getKey(String imageId) {
return CACHE_KEY_PREFIX + imageId;
}
public static String http2httpsProtocal(String url){
if(StringUtils.isBlank(url)) return url;
return url.replaceAll("http://", "https://");
}
public static String imgBase64(String imgURL) throws Exception {
String encodeToString = null;
for (int i = 1; i <= 5; i++) {
ByteArrayOutputStream outPut = null;
InputStream inputStream = null;
byte[] data = new byte[1024];
try {
outPut = new ByteArrayOutputStream();
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new BusinessException("连接失败/链接失效/图片不存在");//
}
inputStream = conn.getInputStream();
int len = -1;
while ((len = inputStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inputStream.close();
// 对字节数组Base64编码
encodeToString = Base64.getEncoder().encodeToString(outPut.toByteArray());
return encodeToString;
} catch (IOException e) {
//e.printStackTrace();
if (5 == i) {
throw new BusinessException(imgURL + ",地址重试5次失败!!!");
}
} finally {
if (null != inputStream) {
inputStream.close();
}
if (null != outPut) {
outPut.flush();
outPut.close();
}
}
}
throw new BusinessException(imgURL + ",地址文件下载失败!!!");
}
/**
* 检查上传图像大小
*
* @param imageURL
* @throws IOException
*/
public static String checkUploadPictureSize(String imageURL) throws IOException {
URL url = new URL(imageURL);
BufferedImage sourceImg = ImageIO.read(url);
int width = sourceImg.getWidth();
int height = sourceImg.getHeight();
if (width > MAX_WIDTH || height > MAX_HEIGHT) {
return "上传照片宽度和高度不符合要求, 图片最大宽度或高度不能超过5000px, " + imageURL;
}
if (width < MIN_WIDTH || height < MIN_HEIGHT) {
return "上传照片宽度和高度不符合要求,图片最小宽度或高度不能低于330px, " + imageURL;
}
return null;
}
}
Java 图片工具类
于 2023-02-28 11:25:26 首次发布