问题
I am uploading images using servlet. To perform resize operations i am converting InputStream to BufferedImage. Now i want to save it in mongoDB. Since, i am new to mongoDB as far as i know, GridFS takes InputStream.
So, is there any way to convert BufferedImage to InputStream?
回答1:
You need to save the BufferedImage to a ByteArrayOutputStream using the ImageIO class, then create a ByteArrayInputStream from toByteArray()
.
回答2:
BufferedImage
➙ ByteArrayOutputStream
➙ byte[]
➙ ByteArrayInputStream
Use the ImageIO.write method to make a BufferedImage (which is a RenderedImage) into a ByteArrayOutputStream. From there get a byte array (byte[]
), feeding that into an InputStream of type ByteArrayInputStream.
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImage, "jpeg", os); // Passing: (RenderedImage im, String formatName, OutputStream output)
InputStream is = new ByteArrayInputStream(os.toByteArray());
Both the ByteArrayOutputStream
and InputStream
implement AutoCloseable. So you can conveniently have those closed automatically by using try-with-resources syntax.
回答3:
First of all you must get your "bytes":
byte[] buffer = ((DataBufferByte)(bufferedImage).getRaster().getDataBuffer()).getData();
And then use ByteArrayInputStream(byte[] buf) constructor to create your InputStream;
回答4:
By overriding the method toByteArray()
, returning the buf
itself (not copying), you can avoid memory related problems. This will share the same array, and 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.
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());
来源:https://stackoverflow.com/questions/4251383/how-to-convert-bufferedimage-to-inputstream