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;
     }
 

转载于:https://www.cnblogs.com/hxxy2003/p/3152986.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值