1,Android读取不同位置(drawable,asset,SDCard)的图片资源
(1)已将图片保存到drawable目录下,通过图片id获得Drawable或者Bitmap
//通过图片id获得Drawable
Drawable drawable=getResource().getDrawable(R.drawable.xxx);
//通过图片id获得Bitmap
Resource res=gerResource();
Bitmap bitmap=BitmapFactory.decodeResource(res, id);
(2)已将图片保存到assest目录下,知道图片的名称,通过inputstream获得图片Drawabl或者 Bitmap
AssetManager asm=getAssetMg();
InputStream is=asm.open(name);//name:图片的名称
//获得Drawable
Drawable da = Drawable.createFromStream(is, null);
//获得Bitmap
Bitmap bitmap=BitmapFactory.decodeStream(is);
(3)图片保存在sdcard,通过图片的路径
String imgFilePath = Environment.getExternalStorageDirectory().toString()+ “/DCIM/device.png”;
fis = new FileInputStream(new File(imgFilePath));//文件输入流
Bitmap bmp = BitmapFactory.decodeStream(fis);
Drawable da = Drawable.createFromStream(is, null)
ImageView iv = (ImageView) findViewById(R.id.image);
Bitmap bit = BitmapFactory.decodeFile(/sdcard/android.bmp);
iv.setImageBitmap(bit);
iv.setImageDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), camera.jpg).getAbsolutePath()));
2,比较Drawable与Bitmap占用内存大小
//测试加载10000个Drawable对象的代码
public class MainActivity extends Activity {
int number = 10000;
Drawable[] array;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
array = new BitmapDrawable[number];
for(int i = 0; i < number; i++)
{
Log.e("", "测试第" + (i+1) + "张图片");
array[i] = getResources().getDrawable(R.drawable.ic_launcher);
}
}
//测试加载10000个Bitmap对象的代码
public class MainActivity extends Activity {
int number = 10000;
Bitmap bitmap[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bitmap = new Bitmap[number];
for (int i = 0; i < number; i++)
{
Log.e("", "测试第" + (i+1) + "张图片");
bitmap[i] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
}
//使用decodeStream加载10000个Bitmap对象的代码
public class MainActivity extends Activity {
int number = 10000;
Bitmap bitmap[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bitmap = new Bitmap[number];
for (int i = 0; i < number; i++)
{
Log.e("", "测试第" + (i+1) + "张图片");
bitmap[i] = BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.ic_launcher));
}
}
总结:加载无论从时间上还是空间上由好到差依次为:
getDrawable(R.drawable.img) > decodeStream >decodeResource