将Image转换为byte

时间:2013-10-22 09:53:26

标签: java

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

    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)???

2 个答案:

答案 0 :(得分:0)

包括此行并检查: -

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

答案 1 :(得分: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;
}

然后你将拥有一个可以写入字节数组的BufferedImage

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;
}
相关问题