1

I want to resize an image and then to write it back to outputstream, for this I need to convert the scaled image into bytes, how can I convert it?

    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

how to fix outputStream.write(newImg)???

coure2011
  • 40,286
  • 83
  • 216
  • 349
  • 1
    http://stackoverflow.com/questions/3211156/how-to-convert-image-to-byte-array-in-java – Raúl Oct 22 '13 at 09:57
  • its not BufferedImage I want to write on outputstream, its scaled instance of it and its type is Image. How to convert Image to byte[] – coure2011 Oct 22 '13 at 09:59
  • I don't see how converting Image to byte[] should be a problem, just google it. – Raúl Oct 22 '13 at 10:11

2 Answers2

0

Include this line and check:-

ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", outputStream);
byte[] imageInByte=outputStream.toByteArray();
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
0

Use this method for scaling:

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;
}

Then you'll have a BufferedImage which you can write to a byte array

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;
}
A4L
  • 17,353
  • 6
  • 49
  • 70