2

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

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

4

3 回答 3

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

于 2013-04-11T07:59:47.467 回答
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" />
于 2013-04-11T08:39:05.937 回答
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" />
于 2013-04-11T08:11:18.687 回答