Ser*_*Amo 7 java image image-scaling
我上传了一个带有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
}
Run Code Online (Sandbox Code Playgroud)
任何人都知道一个简单的功能吗?
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");
}
}
Run Code Online (Sandbox Code Playgroud)
如果你像我一样用尽tomcat中的Java堆空间,请增加tomcat使用的堆空间.如果你使用Eclipse的tomcat插件,接下来应该适用:
在Eclipse中,选择Window> Preferences> Tomcat> JVM Settings
将以下内容添加到JVM Parameters部分
-Xms256m -Xmx512m
Kev*_*ose 21
取决于数据格式.
但是,如果您使用的是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");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15814 次 |
| 最近记录: |