我上传了一个带有 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 插件,下一步应该适用:
In Eclipse, choose Window > Preferences > Tomcat > JVM Settings
Add the following to the JVM Parameters section
-Xms256m -Xmx512m
最佳答案
取决于数据格式。
但是,如果您使用的是 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");
}
}
关于java - 缩放在 Java 中存储为 byte[] 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1228381/