我上传了一个带有struts表单的文件。我把图像作为一个byte [],我想缩放它。
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中,选择Window> 偏好> Tomcat> JVM设置
将以下内容添加到JVM 参数部分
-Xms256m -Xmx512m
答案 0 :(得分:20)
取决于数据格式。
但是,如果您使用的是JPEG,GIF,PNG或BMP,则可以使用ImageIO类。
类似的东西:
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");
}
}
答案 1 :(得分:2)