开发者

Save a BufferedImage object to Amazon S3 as a file

I currently make use of the following to upload a file to S3:

File file = new File(m开发者_StackOverflow社区y_file_path);

AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(cred));

s3.putObject(new PutObjectRequest("folder", key, file));

The above works fine but I want to directly save a BufferedImage to S3 to shave a few seconds from my application but I have no clue on how to do this? This is how I currently save my image to a file:

image = new BufferedImage(rawImage.width, rawImage.height, BufferedImage.TYPE_INT_ARGB);

File file = new File(filepath); 

ImageIO.write(image, "png", file);

Is there a way to do the writing directly to Amazon S3 as a stream, if so, can someone show an example?

In addition, is this a good idea? If its prone to errors, I'll stick to my current method. Any advice appreciated.


The following (or something very similar) should work fine. Avoiding the step of writing to a physical file should be slightly less error-prone than dealing with disk I/O (at the very least, your chances of filling up your disk over time are reduced).

BufferedImage image = ...
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
byte[] buffer = os.toByteArray();
InputStream is = new ByteArrayInputStream(buffer);
AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(cred));
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(buffer.length);
s3.putObject(new PutObjectRequest("folder", key, is, meta));


I would highly recommend using the TransferManager API in the AWS SDK. You can read more about it at the AWS blog post. The following is a snippet regarding its advantage:

Behind this simple API, TransferManager is doing a lot of work for you. Depending on the size and data source for your upload, TransferManager adjusts the algorithm it uses to process your transfer, in order to get the best performance and reliability. Whenever possible, uploads are broken up into multiple pieces, so that several pieces can be sent in parallel to provide better throughput. In addition to higher throughput, this approach also enables more robust transfers, since an I/O error in any individual piece means the SDK only needs to retransmit the one affected piece, and not the entire transfer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜