• 安卓中图片资源的获取和转换


    //1,已将图片保存到drawable目录下
    
    //通过图片id获得Drawable
    
    Resource res=gerResource();
    Drawable drawable=res.getDrawable(id);//id为R.drawable.图片名称
    
    //通过图片id获得Bitmap
    
    Resource res=gerResource();
    
    Bitmap bitmap=BitmapFactory.decodeResource(res, id);
    
    //若只知道图片的名称,可以通过图片的名称获得图片的id
    
    //name:图片的名称 defType:图片的类型(png,jpeg),defPackage:工程的包名
    int id =int id =res.getIdentifier(name, defType, defPackage);
    //获得id之后可以根据你的需要来获得Bitmap或Drawable
    
    //2,已将图片保存到assest目录下
    
    //知道图片的名称,通过inputstream打开图片
    
    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 path = Environment.getExternalStorageDirectory().toString()+ "/DCIM/device.png";
    RandomAccessFile mMiniThumbFile;
    File imgfile = new File(path);
    try {
        mMiniThumbFile = new RandomAccessFile(imgfile, "rw");
    } catch (IOException ex) {
    // Open as read-only so we can at least read the existing
    // thumbnails.
    try {
    mMiniThumbFile = new RandomAccessFile(imgfile, "r");
    } catch (IOException ex2) {
    // ignore exception
    System.out.println(ex2.toString());
    }
    }
    data= new byte[10553];
    try {
    mMiniThumbFile.seek(0);
    int got = mMiniThumbFile.read(data, 0, 10552);
    System.out.println("got="+got);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(e.toString());
    }
    if (data != null) {
    //通过data获得bitmap
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
    
     
    
     
    
        //最简单的方法
    
            String filepath = "/sdcard/paiyipai.jpg";
            Bitmap bm = BitmapFactory.decodeFile(filepath);
    
            //BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
            BitmapDrawable bd=new BitmapDrawable(bm);
            ImageView.setBackgroundDrawable(bd);
  • 相关阅读:
    ansible api调用详解
    多线程使用不当导致的 OOM
    常用Excel工具小结
    lazarus 检测内存泄漏
    用lazarus创建linux的菜单、桌面快捷方式及文件关联
    tkinter窗口程序设计
    vim 从嫌弃到依赖(23)——最后的闲扯
    vim 从嫌弃到依赖(22)——自动补全
    从零开始匹配vim(0)——vimscript 简介
    vim 从嫌弃到依赖(21)——跨文件搜索
  • 原文地址:https://www.cnblogs.com/cfas/p/5150750.html
Copyright © 2020-2023  润新知