サーブレットを使用して画像をアップロードしています。サイズ変更操作を実行するために、InputStream を BufferedImage に変換しています。今、mongoDBに保存したいと思います。私が知る限り、mongoDB は初めてなので、GridFS は InputStream を使用します。
では、BufferedImage を InputStream に変換する方法はありますか?
サーブレットを使用して画像をアップロードしています。サイズ変更操作を実行するために、InputStream を BufferedImage に変換しています。今、mongoDBに保存したいと思います。私が知る限り、mongoDB は初めてなので、GridFS は InputStream を使用します。
では、BufferedImage を InputStream に変換する方法はありますか?
You need to save the BufferedImage to a ByteArrayOutputStream
using the ImageIO
class, then create a ByteArrayInputStream
from toByteArray()
.
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;
method をオーバーライドし、 (コピーではなく) それ自体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());