我有一些图像要在应用程序中显示(当用户从中选择图像时,例如从图库中选择)。
问题是如何复制我放在资产中的图像 代码中的文件夹到SD卡上的文件夹。
编辑:我试过这个例子:http://www.technotalkative.com/android-copy-files-from-assets-to-sd-card/
我已授予应用程序读写权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
答案 0 :(得分:3)
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
获取AssetManager
并使用您要复制的文件名作为参数调用open
。
然后你可以简单地以这种方式复制
File out = new File(Environment.getExternalStorageDirectory(), fileName);
byte[] buffer = new byte[BUFFER_LEN];
FileOutputStream fos = new FileOutputStream(out);
int read = 0;
while ((read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close()
is.close()
请记得在WRITE_EXTERNAL_STORAGE
文件中添加AndroidManifest.xml
权限
答案 1 :(得分:2)
private void copyFileAssets() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("ceo.jpg");
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+ "abc.jpg");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
您必须添加此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 2 :(得分:0)
例如:
Bitmap bitmap = BitmapFactory.decodeResource(resource, id); // get your bitmap that you want to save on SD card.
String compressedFilePath = Environment.getExternalStorageDirectory() + File.separator + "FOLDERNAME" + File.separator + "FILENAME.jpg";
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(pathToStore))); // use 100 to make sure image quality is not reduced(Read the docs)
注意:您需要写入(以及将来可能会读取)写入SDCARD的访问权。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />