歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 圖像系列: 將本地圖片加載到Drawable

Android 圖像系列: 將本地圖片加載到Drawable

日期:2017/3/1 10:11:10   编辑:Linux編程

Android 圖像系列: 將本地圖片加載到Drawable

  1. /**
  2. * 將文件生成位圖
  3. * @param path
  4. * @return
  5. * @throws IOException
  6. */
  7. public BitmapDrawable getImageDrawable(String path)
  8. throws IOException
  9. {
  10. //打開文件
  11. File file = new File(path);
  12. if(!file.exists())
  13. {
  14. return null;
  15. }
  16. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  17. byte[] bt = new byte[BUFFER_SIZE];
  18. //得到文件的輸入流
  19. InputStream in = new FileInputStream(file);
  20. //將文件讀出到輸出流中
  21. int readLength = in.read(bt);
  22. while (readLength != -1) {
  23. outStream.write(bt, 0, readLength);
  24. readLength = in.read(bt);
  25. }
  26. //轉換成byte 後 再格式化成位圖
  27. byte[] data = outStream.toByteArray();
  28. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// 生成位圖
  29. BitmapDrawable bd = new BitmapDrawable(bitmap);
  30. return bd;
  31. }
Copyright © Linux教程網 All Rights Reserved