How to Transform a Bitmap into java.io.file to send to Amazon S3

3

I'm having trouble sending a Bitmap to Amazon S3 using the amazon S3's own SDK.

To send something to Amazon S3 you need to be a file, such as transforming Bitmap into java.io.file to be able to send through TransferObserver .

Reference: link

    
asked by anonymous 14.12.2015 / 18:38

1 answer

3

I also use the amazon SDK to upload to S3 and write Bitmap to a folder in the app cache and then I move to the SDK.

Something like:

@NonNull
public static File storeOnCache(Context context, Bitmap bitmap) throws IOException {
    File cacheDir = context.getCacheDir();
    File file = new File(cacheDir, generateRandomFilename("jpg"));

    FileOutputStream out = new FileOutputStream(file);

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

    out.flush();
    out.close();

    return file;
}

Where generateRandomFileName is a simple method that generates a name to not have conflict.

@NonNull
public static String generateRandomFilename(@Nullable String extension) {
    return new StringBuilder(50)
            .append(System.currentTimeMillis())
            .append((int) (Math.random() * 10000.0))
            .append(".")
            .append(extension)
            .toString();
}

It may be worthwhile to have a later treatment to remove the file at the end of the upload.

Using:

Bitmap bitmap = ...

File bitmapOnCache = storeOnCache(this, bitmap);
String fileName = bitmapOnCache.getName();

// Dependendo da forma como irá fazer:

ObjectMetadata metadata = new ObjectMetadata();

metadata.setContentLength(mTotalFileBytes = bitmapOnCache.length());
metadata.setContentType("image/".concat(getExtension(fileName)));

PutObjectRequest por = new PutObjectRequest("BUCKET_NAME", fileName, new FileInputStream(bitmapOnCache), metadata);

AmazonS3Client client = ...

client.putObject(por);
    
14.12.2015 / 21:38