2013-10-22 79 views
1

我想调整图像大小,然后将其写回输出流,为此我需要将缩放后的图像转换为字节,我该如何转换它?将图像转换为字节

ByteArrayInputStream bais = new ByteArrayInputStream(ecn.getImageB()); 
    BufferedImage img = ImageIO.read(bais); 
    int scaleX = (int) (img.getWidth() * 0.5); 
    int scaleY = (int) (img.getHeight() * 0.5); 
    Image newImg = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH); 

    outputStream.write(newImg); //cannot resolve 

如何修复outputStream.write(newImg)???

+1

http://stackoverflow.com/questions/3211156/how-to-convert-image-to-byte-array-in-java –

+0

它没有BufferedImage我想在outputstream上编写它的缩放实例,它的类型是Image。如何将图像转换为字节[] – coure2011

+0

我不明白如何将图像转换为字节[]应该是一个问题,只是谷歌它。 –

回答

0

使用此方法进行缩放:

public static BufferedImage scale(BufferedImage sbi, 
    int imageType, /* type of image */ 
    int destWidth, /* result image width */ 
    int destHeight, /* result image height */ 
    double widthFactor, /* scale factor for width */ 
    double heightFactor /* scale factor for height */) 
{ 
    BufferedImage dbi = null; 
    if(sbi != null) { 
     dbi = new BufferedImage(destWidth, destHeight, imageType); 
     Graphics2D g = dbi.createGraphics(); 
     AffineTransform at = AffineTransform.getScaleInstance(widthFactor, heightFactor); 
     g.drawRenderedImage(sbi, at); 
    } 
    return dbi; 
} 

然后你就会有,你可以写一个字节数组

public static byte[] writeToByteArray(BufferedImage bi, String dImageFormat) throws IOException, Exception { 
    byte[] scaledImageData = null; 
    ByteArrayOutputStream baos = null; 
    try { 
     if(bi != null) { 
      baos = new ByteArrayOutputStream(); 
      if(! ImageIO.write(bi, dImageFormat, baos)) { 
       throw new Exception("no appropriate writer found for the format " + dImageFormat); 
      } 
      scaledImageData = baos.toByteArray(); 
     } 
    } finally { 
     if(baos != null) { 
      try { 
       baos.close(); 
      } catch(Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return scaledImageData; 
} 
一个BufferedImage
0

包含这一行,并检查: -

ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); 
ImageIO.write(originalImage, "jpg", outputStream); 
byte[] imageInByte=outputStream.toByteArray(); 
+0

我在哪里缩放图像????? – coure2011