Android 图像系列: 将本地图片加载到Drawable


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.           
  17.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  18.         byte[] bt = new byte[BUFFER_SIZE];  
  19.           
  20.         //得到文件的输入流   
  21.         InputStream in = new FileInputStream(file);  
  22.           
  23.         //将文件读出到输出流中   
  24.         int readLength = in.read(bt);  
  25.         while (readLength != -1) {  
  26.             outStream.write(bt, 0, readLength);  
  27.             readLength = in.read(bt);  
  28.         }  
  29.           
  30.         //转换成byte 后 再格式化成位图   
  31.         byte[] data = outStream.toByteArray();  
  32.         Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// 生成位图   
  33.         BitmapDrawable bd = new BitmapDrawable(bitmap);  
  34.           
  35.         return bd;  
  36.     }  

相关内容