4

I load an image from URLusing Picasso library. I want to get the real image size, but I can only get the image size in memory:

Picasso.with(this)
    .load(imageUrl)
    .error(R.drawable.no_image)
    .into(photoView, new Callback() {
        @Override
        public void onSuccess() {
            Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();
            textImageDetail.setText(bitmap.getByteCount());// image size on memory, not actual size of the file
        }

        @Override
        public void onError() { }
    });

How to get the size of the loaded image? I think it is stored somewhere in a cache, but I do not know how to access the image file.

Update

Sorry for my bad English, maybe I asked the wrong question. I need to get the image size (128 kb, 2 MB, etc.). NOT the image resolution (800x600, etc.)

Mikhail
  • 2,612
  • 3
  • 22
  • 37

2 Answers2

3

You could first get the actual Bitmap image that is getting loaded, and then find the dimensions of that. This has to be run in an asynchronous method like AsyncTask because downloading the image is synchronous. Here is an example:

Bitmap downloadedImage = Picasso.with(this).load(imageUrl).get();
int width = downloadedImage.getWidth();
int height = downloadedImage.getHeight();

If you want to get the actual image size in bytes of the Bitmap, just use

// In bytes
int bitmapSize = downloadedImage.getByteCount();
// In kilobytes
double kbBitmapSize = downloadedImage.getByteCount() / 1000;

Replace the imageUrl with whatever URL you want to use. Hope it helps!

AkashBhave
  • 749
  • 4
  • 12
  • 8
    Thanks for the answer, but it does not solve my problem. This in memory image size, not actual size of the file. All 1920x1080 px images return 8294400 bytes (because (1920 px * 1080 px) * 4 bytes per pixel = 8,294,400 bytes). – Mikhail May 23 '16 at 10:07
0

I know this question is old, but I stepped here for an answer and found none.

I found a solution that worked with me using OkHttpClient.

You can fetch the header information only, using OkHttpClient and get the content length without downloading the image.

OkHttpClient httpClient = new OkHttpClient();

Request request = new Request.Builder().url(imageURL).head().build();
Response response = null;

try {
    response = httpClient.newCall(request).execute();
    String contentLength = response.header("content-length");
    int size = Integer.parseInt(contentLength);
} catch (IOException e ) {
    if (response!=null) {
        response.close();
    }
}

Notes:

  • the above code performs a network call, it should be executed on a background thread.
  • size is returned in Bytes, you can divide by 1000 if you want it in KB.
  • this may not work with large files.
  • Beware, casting to integer could bypass the integer's max value.
Khaled
  • 542
  • 1
  • 5
  • 10