简体   繁体   中英

About java ByteArrayOutputStream class

BufferedImage bufferedImage = ImageIO.read(new File("/...icon.jpg"));

// this writes the bufferedImage into a byte array called resultingBytes
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

ImageIO.write(bufferedImage, "jpg", byteArrayOut);

byte[] resultingBytes = byteArrayOut.toByteArray();

I use the above code to get a JEPG image as a byte array. I want to know what exactly is in this byte array. Does this array contain any file header information or just pixel values? And for example, if I want to reverse this image's color, what is a good way to do so? Thanks so much!

It's a complete JPEG file, in memory.

EDIT: If you want to manipulate pixel data as an array, you may find Raster more helpful:

Eg:

Raster raster = bufferedImage.getData();

You can then call one of the Raster.getPixels methods.

Here is how you read real pixel values. The JPEG information is much harder to do anything with!

public static void main(String... args) throws IOException {
    String u = "http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png";

    BufferedImage old = ImageIO.read(new URL(u));
    BufferedImage inverted = new BufferedImage(old.getWidth(),
                                               old.getHeight(),
                                               BufferedImage.TYPE_INT_RGB);


    for (int y = 0; y < old.getHeight(); y++) {
        for (int x = 0; x < old.getWidth(); x++) {
            Color oldColor = new Color(old.getRGB(x, y));

            // reverse all but the alpha channel
            Color invertedColor = new Color(255 - oldColor.getRed(),
                                            255 - oldColor.getGreen(),
                                            255 - oldColor.getBlue());

            inverted.setRGB(x, y, invertedColor.getRGB());
        }
    }

    ImageIO.write(inverted, "png", new File("test.png"));
}

The ByteArrayOutputStream contains whatever you wrote to it. Nothing more, nothing less. So your question is really about ImageIO.write(). Which writes out an encoding of an image according to the encoding type you supply. Which was JPEG.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM