How to create a new file containing an image from drawable in android?

4.1k views Asked by At

I need pick an image from Drawable directory. My code is :

private  void CreateViewForIndex(View rootView, int index) {
    // Instantiate GPUImageView object          
    ImageView mGPUImageView = (ImageView)rootView.findViewById(R.id.image); 

    // Set an image from file inside GPUImageView object    
    File imageFile = new File("/MainActivity/res/drawable-hdpi/russia.jpeg");               
    mImageView.setImage(imageFile);

    // Apply filter
    mImageView.setFilter(returnFilterForIndex(index));
}       

Where rootView is the View. I need to create a new File object from an image in the following directory: /MainActivity/res/drawable-hdpi/russia.jpeg. The problem is that I am unable to get the right directory for the previous image file so the jpeg is never displayed.

1

There are 1 answers

0
Dalija Prasnikar On

You can use following code to create file from drawable resource as-is without any additional encoding-decoding involved in the process. In this code file is saved into application private cache, but this can be easily modified to accommodate saving to any file.

public File createFileFromResource(int resId, String fileName)
{
    File f;
    try
    {
        f = new File(getCacheDir() + File.separator + fileName);
        InputStream is = getResources().openRawResource(resId);
        OutputStream out = new FileOutputStream(f);

        int bytesRead;
        byte[] buffer = new byte[1024];
        while((bytesRead = is.read(buffer)) > 0)
        {
            out.write(buffer, 0, bytesRead);
        }

        out.close();
        is.close();
    }
    catch (IOException ex)
    {
        f = null;
    }
    return f;
}

You can use above method like this:

private void CreateViewForIndex(View rootView, int index) 
{
    // Instantiate GPUImageView object          
    GPUImageView mGPUImageView = GPUImageView)rootView.findViewById(R.id.image); 

    // Set an image from file inside GPUImageView object    
    File imageFile = new File(R.drawable.russia, "russia.jpeg"); 
    if (imageFile != null) 
    {           
        mImageView.setImage(imageFile);    
        // Apply filter
        mImageView.setFilter(returnFilterForIndex(index));
    }
}  

When you are no longer using created cache file it would be good to delete it in order to minimize your app storage use with

imageFile.delete();

or you can clean all cached files on app exit with

public void deleteInternalCacheFiles()
{
    File[] cacheFiles = getCacheDir().listFiles();
    for (File file : cacheFiles)
    {
        file.delete();
    }
}

However, if you cache only small number of files and/or those files do not occupy too much memory, you can safely skip that part.