How do use use Picasso library while downloading images from Amazon S3?

2.6k Views Asked by At

I am storing my images on Amazon S3. I use the following code to download image from Amazon S3

 S3ObjectInputStream content = s3Client.getObject("bucketname", url).getObjectContent();
                byte[] bytes ;
                bytes = IOUtils.toByteArray(content);
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
                bitmap = CommonUtilities.getRoundedCornerBitmap(bitmap, 30);
                cache.put(url, new SoftReference<Bitmap>(bitmap));
                return bitmap;

While going through Picasso documentation, I read that to load images we simply need to do

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

So how to download Amazon S3 images through Picasso.

2

There are 2 best solutions below

0
Nikola Despotoski On

You are getting the InputStream of the S3Object, which will give bytes representation of that object. Instead, you need to build URI from to the S3Object. As far as I know the url is build in following manner:

S3_END_POINT + bucket + key.

Check the use of S3Object redirect location (S3 gives different endpoint url, depending on your location)

Therefore:

String S3_END_POINT = "https://s3.amazonaws.com/"; // public files
S3Object s3Object = s3Client.getObject("bucketname", url);
String url = S3_END_POINT + s3Object.getBucketName() + SLASH + s3Object.getKey();
Picasso.with(context).load(url).into(imageView);
2
Yangfan On

You can use AmazonS3.generatePresignedUrl(String, String, Date) to generate a presigned url and pass it to Picasso. Here is an example "Generate a Pre-signed Object URL using AWS SDK for Java". Though the example is for the Java SDK, it's applicable for the AWS Android SDK.