Android加载图片的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/izzxacbbt/article/details/83628821

android中图片分为Drawable和Bitmap,两者可以相互转化,我们在res目录下放的Image图片都可以通过R类索引得到对应的Drawable,而assets目录则不会生成id,raw目录会生成id但不能直接通过findViewById().

现在讨论获得图片的几种方式

一,获得res/raw目录下的原始图片文件

InputStream is = getResources().openRawResource(R.id.fileNameID) ;

  Bitmap bmp=BitmapFactory.decodeStream(is);

虽然raw目录下的图片文件不加载到内存中,但是他也会生成R类中的ID所以方便使用.

二,获得assets目录下的图片文件

法一

bitmap = BitmapFactory.decodeStream(getAssets().open("example.jpg"));

getAssets().open()返回assets文件对应的文件流.

法二

BitmapDrawable bmp=new BitmapDrawable(getAssets().open("andorra.jpg"));

bitmap=bmp.getBitmap()

三,获得sd卡中的图片

File file = new File(Environment.getExternalStorageDirectory(), name);
if(!file.exists()) return ;
BitmapFactory.Options opts = new BitmapFactory.Options();
//设置为true,代表加载器不加载图片,而是把图片的宽高读出来
opts.inJustDecodeBounds=true;
BitmapFactory.decodeFile(file.getAbsolutePath(), opts);

int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
//得到屏幕的宽高
Display display=getWindowManager().getDefaultDisplay();
DisplayMetrics displayMetrics=new DisplayMetrics();
display.getMetrics(displayMetrics);
//获得像素大小
int screenWidth=displayMetrics.widthPixels;
int screenHeight=displayMetrics.heightPixels;

int widthScale=imageWidth/screenWidth;
int heightScale=imageHeight/screenHeight;
int scale = widthScale > heightScale ? widthScale : heightScale;
opts.inJustDecodeBounds=false;
opts.inSampleSize=scale;
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);

其实核心代码就是BitmapFac.decodeFile(file.getAbsolutePath(),opts);这里面的其他代码是防治oom

四,从资源ID直接获取

BitmapFactory.decodeResource(res, resId);//这里面的res就是activity的getResources(),resid就是图片id

五,通过文件

BitmapFactory.decodeFile(pathName);

六,通过字节数组

private Bitmap BytesToBitmap(byte[] b)
{
    if (b.length != 0) {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    } else {
        return null;
    }
}

七,通过字节流

其实这个在上面那些早就见过了

 BitmapFactory.decodeStream(inputStream);

将资源id转为Drawable

Resources resources = mContext.getResources();
Drawable drawable = resources.getDrawable(R.drawable.a);
imageview.setBackground(drawable);

从raw文件获得Drawable和bmp

Resources r = this.getContext().getResources();
Inputstream is = r.openRawResource(R.drawable.my_background_image);
BitmapDrawable  bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();

从raw文件获得Drawable和bmp

InputStream is = getResources().openRawResource(R.drawable.icon);  

Bitmap mBitmap = BitmapFactory.decodeStream(is);

 
 
 

猜你喜欢

转载自blog.csdn.net/izzxacbbt/article/details/83628821