Sunday, July 17, 2022

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

Issue

I have a task in which I want to get drawable GIF image path but i am not getting correct path I tried below code to set path.

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

but It's not working it's not giving me correct image but when i tried to get path from SD Card with below code

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

it's working.

So now I am trying to store gif images from drawable or assets from SD card or internal memory. I found below code to copy PNG or JPEG to SD card.

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

but not getting any way to copy GIF image. Any suggestions welcome.


Solution

Indeed you will not get a path from such a resource id. Instead you can get an InputStream from such a resource and use that stream to read the contents and copy for instance to a real file or whatever.

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

The type of the file does not matter. And as soon as you have this 'copy file' working you can throw away the code for copying jpg and png as it uses an intermediate Bitmap which is a bad idea and will change the file content and you end up with a different file -size-.



Answered By - greenapps
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.