Android获取图片与图片的存放

来源:互联网 发布:网络谣言典型案例 编辑:程序博客网 时间:2024/06/02 16:25
一、Android图片存放的4种方式
1. 图片放在sdcard中,

  Bitmap imageBitmap = BitmapFactory.decodeFile(path) (path 是图片的路径,跟目录是/sdcard)
2. 图片在项目的res文件夹下面
  //得到application对象
  ApplicationInfo appInfo = getApplicationInfo();
  //得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录,appInfo.packageName是应用程序的包)
  int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);
  //代码如下
  public Bitmap getRes(String name) {
  ApplicationInfo appInfo = getApplicationInfo();
  int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);
  return BitmapFactory.decodeResource(getResources(), resID);
  }
3. 图片放在src目录下
  String path = "com/xiangmu/test.png"; //图片存放的路径
  InputStream is = getClassLoader().getResourceAsStream(path); //得到图片流
4.Android中有个Assets目录,这里可以存放只读文件
  资源获取的方式为

  InputStream is = getResources().getAssets().open(name);


二、Android获得图片资源的三种方式

1) 使用BitmapFactory解析图片
// --> 使用BitmapFactory解析图片
public void myUseBitmapFactory(Canvas canvas){
// 定义画笔
   Paint paint = new Paint();
// 获取资源流
   Resources rec = getResources();
   InputStream in = rec.openRawResource(R.drawable.haha);
// 设置图片
   Bitmap bitmap =BitmapFactory.decodeStream(in);
// 绘制图片
   canvas.drawBitmap(bitmap, 0,20, paint);        

}

2) 使用BitmapDrawable解析图片

// --> 使用BitmapDrawable解析图片
    public void myUseBitmapDrawable(Canvas canvas){
    // 定义画笔
       Paint paint = new Paint();
    // 获得资源
       Resources rec = getResources();
    // BitmapDrawable
       BitmapDrawable bitmapDrawable = (BitmapDrawable) rec.getDrawable(R.drawable.haha);
    // 得到Bitmap
       Bitmap bitmap = bitmapDrawable.getBitmap();
    // 在画板上绘制图片
       canvas.drawBitmap(bitmap, 20,120,paint);
    }
3)使用InputStream和BitmapDrawable绘制
// --> 使用InputStream和BitmapDrawable解析图片
    public void myUseInputStreamandBitmapDrawable(Canvas canvas){
    // 定义画笔
       Paint paint = new Paint();
    // 获得资源
       Resources rec = getResources();
    // InputStream得到资源流
       InputStream in = rec.openRawResource(R.drawable.haha);
    // BitmapDrawable 解析数据流
       BitmapDrawable bitmapDrawable =  new BitmapDrawable(in);
    // 得到图片
       Bitmap bitmap = bitmapDrawable.getBitmap();
    // 绘制图片
       canvas.drawBitmap(bitmap, 100, 100,paint);
    }
原创粉丝点击