Java 如何从 BufferedImage 获取 InputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/649186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an InputStream from a BufferedImage?
提问by fromvega
How can I get an InputStream from a BufferedImage object? I tried this but ImageIO.createImageInputStream() always returns NULL
如何从 BufferedImage 对象获取 InputStream?我试过了,但 ImageIO.createImageInputStream() 总是返回 NULL
BufferedImage bigImage = GraphicsUtilities.createThumbnail(ImageIO.read(file), 300);
ImageInputStream bigInputStream = ImageIO.createImageInputStream(bigImage);
The image thumbnail is being correctly generated since I can paint bigImageto a JPanelwith success.
图像缩略图正在正确生成,因为我可以成功将bigImage 绘制到JPanel。
Thank you.
谢谢你。
采纳答案by TofuBeer
If you are trying to save the image to a file try:
如果您尝试将图像保存到文件中,请尝试:
ImageIO.write(thumb, "jpeg", new File(....));
If you just want at the bytes try doing the write call but pass it a ByteArrayOutputStream which you can then get the byte array out of and do with it what you want.
如果您只想要字节,请尝试执行 write 调用,但将其传递给 ByteArrayOutputStream ,然后您可以从中获取字节数组并对其进行处理。
回答by Felipe
From http://usna86-techbits.blogspot.com/2010/01/inputstream-from-url-bufferedimage.html
来自http://usna86-techbits.blogspot.com/2010/01/inputstream-from-url-bufferedimage.html
It works very fine!
它工作得很好!
Here is how you can make an InputStream for a BufferedImage:
URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif"); BufferedImage image = ImageIO.read(url); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "gif", os); InputStream is = new ByteArrayInputStream(os.toByteArray());
以下是为 BufferedImage 创建 InputStream 的方法:
URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif"); BufferedImage image = ImageIO.read(url); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "gif", os); InputStream is = new ByteArrayInputStream(os.toByteArray());
回答by Igor
By overriding the method toByteArray()
, returning the buf
itself (not copying), you can avoid memory related problems. This will share the same array, not creating another of the correct size. The important thing is to use the size()
method in order to control the number of valid bytes into the array.
通过覆盖方法toByteArray()
,返回buf
自身(而不是复制),您可以避免与内存相关的问题。这将共享相同的数组,而不是创建另一个正确大小的数组。重要的是使用该size()
方法来控制进入数组的有效字节数。
final ByteArrayOutputStream output = new ByteArrayOutputStream() {
@Override
public synchronized byte[] toByteArray() {
return this.buf;
}
};
ImageIO.write(image, "png", output);
return new ByteArrayInputStream(output.toByteArray(), 0, output.size());