如何将 GIF 图像复制到设备内存或在 drawable 中获取正确的 GIF 路径

How to copy GIF image to device memory or getting correct path of GIF in drawable

我有一个任务,我想在其中获取可绘制的 GIF 图像路径,但我没有获得正确的路径我尝试使用下面的代码来设置路径。

 int resId = R.drawable.temp;
 String imagePath2 = "android.resource://"+getPackageName()+"/"+resId;
 String imagePath2 = ("android.resource://my.package.name/drawable/temp.gif");

但它不起作用,它没有给我正确的图像,但是当我尝试使用以下代码从 SD 卡获取路径时

String inputPath = Environment.getExternalStorageDirectory()+ "/temp.gif";

它正在工作。

所以现在我正在尝试存储来自可绘制对象的 gif 图像或来自 SD 卡或内部存储器的资产。我在下面找到了将 PNG 或 JPEG 复制到 SD 卡的代码。

Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

但无法复制 GIF 图像。 欢迎任何建议。

确实,您不会从这样的资源 ID 中获取路径。相反,您可以从此类资源中获取 InputStream 并使用该流读取内容并复制到例如真实文件或其他任何内容。

InputStream is = getResources().openRawResource(R.drawable.temp);

文件的类型无关紧要。一旦你有了这个 'copy file' 工作,你就可以扔掉复制 jpg 和 png 的代码,因为它使用中间位图,这是一个坏主意,会改变文件内容,你最终会得到一个不同的文件 -尺寸-.

我制作了以下获取图像路径的方法,并且效果很好。

int resId = R.drawable.temp;
public String getFilePath(int resId){
   // AssetManager assetManager = getAssets();
    String fileName = "emp.gif";
    InputStream in = null;
    OutputStream out = null;
    File outFile = null;
    try {
        //in = assetManager.open(fileName);
        in = getResources().openRawResource(resId);
        outFile = new File(getExternalFilesDir(null), fileName);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
    } catch(IOException e) {
        Log.e("tag", "Failed to copy asset file: " + fileName, e);
    }
    finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // NOOP
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // NOOP
            }
        }
    }

    return outFile.getAbsolutePath();
}

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