java - 裁剪图像后尺寸变大
问题描述
我从来没有在java中处理过图片,我是这方面的初学者。我需要制作一个函数,根据图像中间的一定宽度和高度比例裁剪图像。
通过 REST Api,我收到一个 MultipartFile,我将其传递给图像裁剪功能。我使用 file.getBytes() 转发图像。
这是我为图像裁剪功能编写代码的方式:
public static byte[] cropImage(byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try {
BufferedImage img = ImageIO.read(bais);
int width = img.getWidth();
int height = img.getHeight();
float aspectRatio = (float) 275 / (float) 160;
int destWidth;
int destHeight;
int startX;
int startY;
if(width/height > aspectRatio) {
destHeight = height;
destWidth = Math.round(aspectRatio * height);
startX = Math.round(( width - destWidth ) / 2);
startY = 0;
} else if (width/height < aspectRatio) {
destWidth = width;
destHeight = Math.round(width / aspectRatio);
startX = 0;
startY = Math.round((height - destHeight) / 2);
} else {
destWidth = width;
destHeight = height;
startX = 0;
startY = 0;
}
BufferedImage dst = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_ARGB);
dst.getGraphics().drawImage(img, 0, 0, destWidth, destHeight, startX, startY, startX + destWidth, startY + destHeight, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(dst, "png", baos);
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("IOException in scale");
}
}
但是当我裁剪图像时,结果是一个比接收到的图像大得多的图像。我需要有关如何解决此问题的帮助。
编辑:
根据这个答案,这部分代码的大小会增加:
ImageIO.read (bais)
有没有其他方法可以将图像从字节数组转换为缓冲图像但保持原始图像的大小?
解决方案
我不知道为什么,但部分原因是问题ImageIO.write(dst, "png", baos);
我正在尝试使用不同类型的图像(png、jpg、jpeg),但只有png
它减小了我的图像大小。在我更改为jpeg
它的情况下,减小了所有图像的大小。
推荐阅读
- react-native - 使用 Realm.Credentials.jwt(token) 进行身份验证时为空对象用户以及 RN 热重载的 Realm 连接问题
- r - 避免在 count() 和 aggregate() 函数之后自动生成列名
- python - 给定字符串的奇数位置和偶数位置的字符,我们如何将它们组合起来得到python中的最终字符串?
- html - 网格内的图像对齐
- javascript - Javascript 不等待“then”表单提交
- javascript - Vue 3:为什么在 Vue 3 模板中引用时 dom 引用值未定义
- cron - cronjob 在完成之前被杀死
- authentication - Kubernetes:如何让另一个人使用编辑 clusterRole 权限访问 Kubernetes 集群?
- javascript - 通过数组访问 javascript 对象值
- spring-batch - SCDF服务器双数据库连接错误