Sidra Arshad
Sidra Arshad

Reputation: 11

how to display images using filename in android

i am using imageAdapter class in which i have an array that stores drawables

public Integer[] mThumbIds = {
                  R.drawable.blue, R.drawable.floral,
                  R.drawable.bluefloral    }; 

in first activity when user click on save button i have saved those images in android internal memory like data/ data/ com.myapp.color , i have get the file name, and file path too and passed it to imageAdapter class i just wanted to know that through this file name and path how can i save these images in to this array. because through this array i am displaying images in gridview.

Upvotes: 1

Views: 833

Answers (2)

Mahmoud
Mahmoud

Reputation: 2893

If the image inside the internal or external storage you can load it by this:

Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);

If the image inside the drawable folder inside the apk you can use:

ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.drawable_name);

If the image inside the assets folder you can use:

InputStream inputStream = getAssets().open("image_name.jpg");
Drawable drawable = Drawable.createFromStream(inputStream, null);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageDrawable(drawable);

If the image inside drawable folder and you have only the name you can get the resource id by using:

int drawableResourceId = this.getResources().getIdentifier("image_name_without_extension", "drawable", this.getPackageName());

Upvotes: 1

Rohit5k2
Rohit5k2

Reputation: 18112

This is how you can get the image id's using their file names. Using this id you can load the image in image view.

If the image name is my_image this method would return id value associated with R.id.my_image

public static int getImageIDFromName(String imageName)
{
    int imageID = 0;
    if(imageName == null
            || imageName.equalsIgnoreCase(""))
    {
        return 0;
    }

    try
    {
        @SuppressWarnings("rawtypes")
        Class res = R.drawable.class;
        Field field = res.getField(imageName);
        imageID = field.getInt(null);
    }
    catch(Exception e)
    {

    }

    return imageID;
}

Upvotes: 0

Related Questions