【发布时间】:2010-11-16 17:39:11
【问题描述】:
我上传了一个带有 struts 表单的文件。我有一个字节[]的图像,我想缩放它。
FormFile file = (FormFile) dynaform.get("file");
byte[] fileData = file.getFileData();
fileData = scale(fileData,200,200);
public byte[] scale(byte[] fileData, int width, int height) {
// TODO
}
有人知道一个简单的函数吗?
public byte[] scale(byte[] fileData, int width, int height) {
ByteArrayInputStream in = new ByteArrayInputStream(fileData);
try {
BufferedImage img = ImageIO.read(in);
if(height == 0) {
height = (width * img.getHeight())/ img.getWidth();
}
if(width == 0) {
width = (height * img.getWidth())/ img.getHeight();
}
Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0,0,0), null);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ImageIO.write(imageBuff, "jpg", buffer);
return buffer.toByteArray();
} catch (IOException e) {
throw new ApplicationException("IOException in scale");
}
}
如果你像我一样在 tomcat 中用完了 Java 堆空间,请增加 tomcat 使用的堆空间。如果你使用 Eclipse 的 tomcat 插件,接下来应该应用:
在 Eclipse 中,选择窗口 > 首选项 > Tomcat > JVM 设置
将以下内容添加到 JVM 参数部分
-Xms256m -Xmx512m
【问题讨论】:
-
在这里猜测:JPEG 不做透明度。将
TYPE_INT_ARGB更改为TYPE_INT_RGB和new Color(0,0,0,0)更改为new Color(0,0,0) -
至于堆空间,您可以通过直接处理输入流而不是将其读入字节数组来节省一些空间。但是,要缩放图像,您需要在内存中复制它(及其缩放版本);所以你可能只需要增加堆空间。查看
java -xmx。
标签: java image image-scaling