有些Android应用须要一些初始化数据,可是考虑到国内这种龟速网络和高昂的网络流量费用,能够将这些初始化数据存在数据库中,有时遇到图片的状况下,能够在初始化的阶段将assets目录下的图片复制到内存中。java
下面是我实现的一个方法:android
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;
}
|