Android復制assets目錄下的圖片到內存


轉自:http://www.chenwg.com/android/android%E5%A4%8D%E5%88%B6assets%E7%9B%AE%E5%BD%95%E4%B8%8B%E7%9A%84%E5%9B%BE%E7%89%87%E5%88%B0%E5%86%85%E5%AD%98.html

有些Android應用需要一些初始化數據,但是考慮到國內這種龜速網絡和高昂的網絡流量費用,可以將這些初始化數據存在數據庫中,有時遇到圖片的情況下,可以在初始化的階段將assets目錄下的圖片復制到內存中。

下面是我實現的一個方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
      * 讀取Assets文件夾中的圖片資源
      * @param context
      * @param fileName
      * @return
      */
     public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
         //獲取應用的包名
         String packageName = context.getPackageName();
         //定義存放這些圖片的內存路徑
         String path= "/data/data/" +packageName;
         //如果這個路徑不存在則新建
         File file =  new File(path);
         Bitmap image =  null ;
         boolean isExist = file.exists();
         if (!isExist){
             file.mkdirs();
         }
         //獲取assets下的資源
         AssetManager am = context.getAssets();
         try {
             //圖片放在img文件夾下
             InputStream is = am.open( "img/" +fileName);
             image = BitmapFactory.decodeStream(is);
             FileOutputStream out =  new FileOutputStream(path+ "/" +fileName);
             //這個方法非常贊
             image.compress(Bitmap.CompressFormat.PNG, 100 ,out);
             out.flush();
             out.close();
             is.close();
         catch (IOException e) {
             e.printStackTrace();
         }
         return image;
     }
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM