2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > java 本地图片压缩 转base64并限制文件大小

java 本地图片压缩 转base64并限制文件大小

时间:2023-09-09 09:01:30

相关推荐

java 本地图片压缩 转base64并限制文件大小

/** 本地图片转base64并限制文件大小@param imagePath 图片全路径@param sizeLimit 大小 整数 限制的大小 KB 1024@return 返回值为0,imageurl为空;返回值为1,imageurl路径不可访问;具体指为转换后的值

*/

public static String convertLocalImageToBase64(String imagePath, Integer sizeLimit) {

Log.debug(“[本地图片转base64]imagePath:{},sizeLimit:{}” + imagePath + sizeLimit);

// 判断路径是否为空

if (StrUtil.isBlank(imagePath)) {

Log.debug(“传入的地址为空!”);

return “0”;

}

// 默认上限为50k

if (sizeLimit == null) {

sizeLimit = 50;

}

sizeLimit = sizeLimit * 1024;

String base64Image = null;

DataInputStream dataInputStream = null;

ByteArrayOutputStream outputStream = null;

ByteArrayInputStream inputStream = null;

try {

FileInputStream fis = new FileInputStream(imagePath);

dataInputStream = new DataInputStream(fis);

outputStream = new ByteArrayOutputStream();

byte[] buffer = new byte[2048];

int length;

while ((length = dataInputStream.read(buffer)) > 0) {

outputStream.write(buffer, 0, length);

}

byte[] context = outputStream.toByteArray();

Log.debug(“[本地图片转base64]byte context”);

// 将图片数据还原为图片

inputStream = new ByteArrayInputStream(context);

BufferedImage image = ImageIO.read(inputStream);

int imageSize = context.length;

int type = image.getType();

int height = image.getHeight();

int width = image.getWidth();

BufferedImage tempImage;

// 判断文件大小是否大于size,循环压缩,直到大小小于给定的值

Log.debug(“[imageSize]” + imageSize + " sizeLimit :" + sizeLimit);

while (imageSize > sizeLimit) {

Log.debug(“[循环压缩]” + imageSize + " ,sizeLimit :" + sizeLimit);

// 将图片长宽压缩到原来的90%

height = new Double(height * 0.9).intValue();

width = new Double(width * 0.9).intValue();

tempImage = new BufferedImage(width, height, type);

// 绘制缩小后的图 //不执行也不报错需要配置下服务器tomcat启动配置 留在文章结尾

Log.debug(“[tempImage]” + tempImage);

tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);

// 重新计算图片大小

outputStream.reset();

boolean wriFlag = ImageIO.write(tempImage, “jpg”, outputStream);

imageSize = outputStream.toByteArray().length;

Log.debug(“[压缩后 imageSize]” + imageSize);

}

// 将图片转化为base64并返回

byte[] data = outputStream.toByteArray();

// 此处一定要使用org.apache.tomcat.util.codec.binary.Base64,防止再linux上出现换行等特殊符号

base64Image = Base64.encodeBase64String(data);

return base64Image;

} catch (Exception e) {

Log.error(“[本地图片转base64][异常]”, e);

} finally {

IoUtil.close(dataInputStream);

IoUtil.close(outputStream);

IoUtil.close(inputStream);

}

Log.debug(“[本地图片转base64]base64Image的长度:{}” + base64Image.length());

return base64Image;

}

//这个不执行困扰了好几天,找了很多说法也换了很多方法都不行,最后在tomcat启动配置项修改了下 竟然成功了

linux下tomcat的启动文件要设置JAVA_OPTS=“-Djava.awt.headless=true”

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。