android: - 如何将图像从Assets复制到SD卡?

时间:2013-04-11 07:54:56

标签: android

我有一些图像要在应用程序中显示(当用户从​​中选择图像时,例如从图库中选择)。

问题是如何复制我放在资产中的图像    代码中的文件夹到SD卡上的文件夹。

3 个答案:

答案 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";

  • 使用压缩方法保存。 (根据docs保存图像的快捷方式)

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" />