0

I prepared images for my android app. I put images which have different sizes to drawable folders because of different device sizes. Now i want to get these from url. I want to get the image that is most appropriate for the device's size. How should I do this? Is there any suggest?

Meryem Uysal
  • 191
  • 1
  • 2
  • 13

1 Answers1

1

From the api, you need to send URI to images of all sizes, then in android you need to download the image that suits the device's dpi value, the code for that is like this:

You can get the density value of your device like this

float density = Resources.getSystem().getDisplayMetrics().density * 160f;

or

float density = context.getResources().getDisplayMetrics().density * 160f;

Then you do a series of if else statements and download the appropriate image from your sever.

if (density == DisplayMetrics.DENSITY_HIGH) {
    return downloadLargeImage();
} else if (density == DisplayMetrics.DENSITY_MEDIUM) {
    return downloadMediumImage();
} else if (density == DisplayMetrics.DENSITY_LOW) {
    return downloadSmallImage();
} else {
    return downloadMediumImage();
}

There are more density values which you can run the if else loop on, I usually just take care of these 3 cases

Or there is another way too, what you can do is send the devices density value to the server along with the get request for the image, and do this if else calculation on the server and return the appropriate image file.

Both methods are effectively same, but the 2nd method is semantically wrong, your server shouldn't be the one deciding which image to send, but instead your device determining which image size to download

Bhargav
  • 8,118
  • 6
  • 40
  • 63
  • Thanks for your answer. It helps me to find answer. But you are not completely right. You are finding density that is float. But it will not equal DisplayMetrics.DENSITY_HIGHT or DisplayMetrics.DENSITY_MEDIUM or DisplayMetrics.DENSITY_LOW etc. it goes always else statement. I researched and found how to find int density. So, I should find density like this : DisplayMetrics metrics = getResources().getDisplayMetrics(); int density = (int)(metrics.density * 160f); – Meryem Uysal Mar 05 '16 at 08:37
  • @MeryemUysal i just fixed you can mark it right now – Bhargav Mar 05 '16 at 09:19