Android 获得图片的方法

已将图片保存到drawable目录下  
       通过图片id获得Drawable  

java代码:
  1. Resource res=gerResource(); 
  2. Drawable drawable=res.getDrawable(id);//id为R.drawable.图片名称 

  3. //通过图片id获得Bitmap 
  4. Resource res=gerResource(); 
  5. Bitmap bitmap=BitmapFactory.decodeResource(res, id); 
  6. //若只知道图片的名称,可以通过图片的名称获得图片的id 
  7. //name:图片的名称 defType:图片的类型(png,jpeg),defPackage:工程的包名 

  8. int id =int id =res.getIdentifier(name, defType, defPackage); 


  9. //获得id之后可以根据你的需要来获得Bitmap或Drawable 

  10. //2,已将图片保存到assest目录下 
  11. //知道图片的名称,通过inputstream打开图片 

  12. AssetManager asm=getAssetMg(); 
  13. InputStream is=asm.open(name);//name:图片的名称 
  14. //获得Drawable 
  15. Drawable da = Drawable.createFromStream(is, null); 

  16. //获得Bitmap 
  17. Bitmap bitmap=BitmapFactory.decodeStream(is); 

  18. //3,图片保存在sdcard,已知图片的路径 
  19. //图片路径 
  20. String path = Environment.getExternalStorageDirectory().toString()+ "/DCIM/device.png"; 
  21. RandomAccessFile mMiniThumbFile; 
  22. File imgfile = new File(path); 
  23. try { 
  24. mMiniThumbFile = new RandomAccessFile(imgfile, "rw"); 
  25. } catch (IOException ex) { 

  26. // Open as read-only so we can at least read the existing 
  27. // thumbnails. 

  28. try { 
  29. mMiniThumbFile = new RandomAccessFile(imgfile, "r"); 
  30. } catch (IOException ex2) { 
  31. // ignore exception 

  32. System.out.println(ex2.toString()); 



  33. data= new byte[10553]; 
  34. try { 
  35. mMiniThumbFile.seek(0); 
  36. int got = mMiniThumbFile.read(data, 0, 10552); 
  37. System.out.println("got="+got); 
  38. } catch (IOException e) { 
  39. // TODO Auto-generated catch block 
  40. e.printStackTrace(); 
  41. System.out.println(e.toString()); 


  42. if (data != null) { 
  43. //通过data获得bitmap 
  44. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值