Android加载图片的几种方式
一,获得res/raw目录下的原始图片文件
InputStream is = getResources().openRawResource(R.id.fileNameID) ;
  Bitmap bmp=BitmapFactory.decodeStream(is);
虽然raw目录下的图片文件不加载到内存中,但是他也会生成R类中的ID所以方便使用.
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;
    }
}
参考资料和推荐阅读:
[1].https://blog.csdn.net/izzxacbbt/article/details/83628821
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号