Android本地图片转换成Bitmap存储

前几天项目中遇到这样一个问题,要做一个表情列表展示,UI给了一套表情图片,都是.jpg格式的,拿到图片之后,首先的思路是应该把这些图片作为数据源存到一个集合中,然后通过适配器就可以展示到GridView列表上了。思路有了,具体该如何实现呢?

这里为了实现简单,我把这一组图片资源放到了项目中的assets目录下面,然后对这些图片资源获取输入流(InputStream),然后借助BitmapFactory这个工厂类中的decodeStream()方法转成Bitmap对象,再通过一组for循环,将这些Bitmap对象存到一个List集合中,具体的实现方法为:

package com.zhibeizhen.antusedcar.bbs.tools;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jarchie on 17/1/6.
 * 创建本地表情的工具类
 */

public class EmojyUtils {
    //表情图片的集合
    private static List<Bitmap> bitmaps;

    /**
     * 通过循环把Assets目录下面的图片一一的添加到Bitmap集合中去
     */
    public static List<Bitmap> addImageToList(Context context){
        bitmaps = new ArrayList<>();
        for (int i = 1;i < 51;i++){
            Bitmap bitmap = getImageFromAssetsFile(context,i+".jpg");
            bitmaps.add(bitmap);
        }
        return bitmaps;
    }

    /**
     * 通过读取Assets目录下面的文件,将其转为Bitmap对象
     * @param fileName
     * @return
     */
    private static Bitmap getImageFromAssetsFile(Context context, String fileName){
        Bitmap image = null;
        AssetManager manager = context.getResources().getAssets();
        try {
            InputStream inputStream = manager.open(fileName);
            image = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

}

然后在我们的Adapter中,我们只需要给对应的ImageView控件设置上图片即可:

hodler.iv.setImageBitmap(list.get(position));

这样就完成了本地图片的列表展示功能。

发布了48 篇原创文章 · 获赞 47 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/JArchie520/article/details/54288143