2009-08-04 16 views
4

我上传带有struts表单的文件。我有图像作为一个字节[],我想缩放它。缩放在Java中存储为字节[]的图像

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 Heap Space,请增加tomcat使用的堆空间。如果您使用的是tomcat Eclipse插件,接下来应该适用于:

在Eclipse中,选择Window> 首选项>的Tomcat> JVM设置

添加以下到JVM 参数部分

-Xms256m -Xmx512m

+1

__Guessing here__:JPEG不做透明度。将`TYPE_INT_ARGB`改为`TYPE_INT_RGB`并将`new Color(0,0,0,0)`改为`new Color(0,0,0)` – 2009-08-04 17:36:13

+1

至于堆空间,您可以通过直接工作来节省一些空间而不是将其读入字节数组中。但是,要缩放图像,您需要将其副本(及其缩放版本)存储在内存中;所以你可能只需要增加堆空间。看看`java -xmx`。 – 2009-08-04 18:47:56

回答

18

取决于数据格式。

但是,如果您使用的是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"); 
     } 
    }