• 关于Android读取不同位置(drawable,asset,SDCard)的图片资源的总结


    方式一:

    已将图片保存到drawable目录下,通过图片id获得Drawable或者Bitmap,此方式最常用。(若只知道图片的名称,还可以通过图片的名称获得图片的id)

    (1)通过图片id获得Drawable

    Drawable drawable=getResource().getDrawable(R.drawable.xxx);

    (2)通过图片id获得Bitmap

    Resource res=gerResource();

    Bitmap bitmap=BitmapFactory.decodeResource(res, id);

    (3)通过图片的名称获得图片的id(两种方法)

     int id =res.getIdentifier(name, defType, defPackage); //name:图片的名,defType:资源类型(drawable,string。。。),defPackage:工程的包名

    Drawable drawable=getResource().getDrawable(id);

    方式二:

    已将图片保存到assest目录下,知道图片的名称,通过inputstream获得图片Drawabl

    或者 Bitmap

    AssetManager asm=getAssetMg();

    InputStream is=asm.open(name);//name:图片的名称

    (1)获得Drawable
    Drawable da = Drawable.createFromStream(is, null);

    (2)获得Bitmap
    Bitmap bitmap=BitmapFactory.decodeStream(is);

    方式三: 图片保存在sdcard,通过图片的路径h

    /图片路径
    String imgFilePath = Environment.getExternalStorageDirectory().toString()
    + “/DCIM/device.png”;

    (1)文件输入流

    fis = new FileInputStream(new File(imgFilePath));//文件输入流

    Bitmap bmp = BitmapFactory.decodeStream(fis);

    (2)

    ImageView iv = (ImageView) findViewById(R.id.image);   
    Bitmap bit = BitmapFactory.decodeFile("/sdcard/Android.bmp");      
    iv.setImageBitmap(bit);

    setImageDrawable方法传入参数是图片的绝对路径,所以直接将图片所在路径直接写入就可以显示了

    iv.setImageDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "camera.jpg").getAbsolutePath()));

     
  • 相关阅读:
    linux中ll和du的区别
    django+celery+redis环境搭建
    python中若干错误
    js正则表达式中匹配反引号
    yii学习小结
    linux下DNS设置以及解析顺序
    apache中若干模块的安装
    HTML基础
    selenium
    selenium
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/5625807.html
Copyright © 2020-2023  润新知