简体   繁体   中英

Create dynamic thumbnail image from drawable resource and set to imageView

I am new to android, i am using some drawable resource image to display in activity. but i want to scale that images to thumbnail size.

my code is :

public class CategoryImages extends BaseAdapter {
    ...
    ...
    Integer[] categoryImagesList;
    public CategoryImages(Context mainActivity, Integer[] categories_images, String selectedCat) {
        categoryImagesList = {R.drawable.suit_7, R.drawable.bkg_4, R.drawable.misc_18};
    }
    public class Holder {
        ImageView iv;
    }
    public View getView(final int position, View convertView, ViewGroup parent) {
        Holder holder = new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.category_image_list, null);
        holder.iv = (ImageView) rowView.findViewById(R.id.category_img);
        holder.iv.setImageResource(categoryImagesList[position]);
    }
    ...
    ...
}

This is working file with actual size of images, but now i change it to below

public class CategoryImages extends BaseAdapter {
    ...
    ...
    Integer[] categoryImagesList;
    public CategoryImages(Context mainActivity, Integer[] categories_images, String selectedCat) {
        categoryImagesList = {R.drawable.suit_7, R.drawable.bkg_4, R.drawable.misc_18};
    }
    public class Holder {
        ImageView iv;
    }
    public View getView(final int position, View convertView, ViewGroup parent) {
        Holder holder = new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.category_image_list, null);
        holder.iv = (ImageView) rowView.findViewById(R.id.category_img);

        Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(categoryImagesList[position]), 100, 100);
        holder.iv.setImageResource(thumbImage);
    }
    ...
    ...
}

then ThumbnailUtils.extractThumbnail showing error with categoryImagesList[position] parameter and also holder.iv.setImageResource not accepting the thumbImage param, it says that thumbImage is of type Bitmap and setImageResource require int

thanks

You need to change two things here :

1) BitmapFactory.decodeFile(categoryImagesList[position]), 100, 100) to BitmapFactory.decodeResource(getResources(),categoryImagesList[position]);

2) Change holder.iv.setImageResource(thumbImage); to holder.iv.setImageBitmap(thumbImage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM