简体   繁体   English

关于java ByteArrayOutputStream类

[英]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. 我使用上面的代码将JEPG图像作为字节数组。 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. 它是一个完整的JPEG文件,在内存中。

EDIT: If you want to manipulate pixel data as an array, you may find Raster more helpful: 编辑:如果您想将像素数据作为数组进行操作,您可能会发现Raster更有帮助:

Eg: 例如:

Raster raster = bufferedImage.getData();

You can then call one of the Raster.getPixels methods. 然后,您可以调用其中一个Raster.getPixels方法。

Here is how you read real pixel values. 以下是您阅读实际像素值的方法。 The JPEG information is much harder to do anything with! JPEG信息更难以做任何事情!

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. ByteArrayOutputStream包含您写入的任何内容。 Nothing more, nothing less. 没有更多,没有更少。 So your question is really about ImageIO.write(). 所以你的问题实际上是关于ImageIO.write()。 Which writes out an encoding of an image according to the encoding type you supply. 根据您提供的编码类型写出图像编码。 Which was JPEG. 这是JPEG。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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