Question

I have to save an image in to a gallery from a drawable resource with a button and I have use this code:

@Override
           public void onClick(View arg0) {
            // TODO Auto-generated method stub


            Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher3);

            //generate file
            String SDdirectory = Environment.getExternalStorageDirectory().getPath();
             File externalStorageDir = Environment.getExternalStorageDirectory();
             File f = new File(externalStorageDir, "Bitmapname.png");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG,0 , bos);
            byte[] bitmapdata = bos.toByteArray();
            try {
                OutputStream os = new FileOutputStream (new File ("storage/sdcard0/iob"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

now the problem is that i save a file of 0kb... o.o

Thanks in advance .

Was it helpful?

Solution

I don't know, if there is a better solution, but this code works for me:

//at first I've imported the bitmap normally.
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.wall);

//generate file
File dir = new File ("/sdcard/foldername/");
File f = new File(dir, String.format("mybitmapname.png"));

//then write it to galery by adding this lines
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 , bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);  
fos.flush();
fos.close();
bos.close();

Please make sure you have added this line in your manifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

OTHER TIPS

Try this:

OutputStream os = new FileOutputStream(new File("path/to/file"));

Beware, though. The way you copy data between the streams may easily lead to heap overflow if the resource is large. You should consider a smaller buffer reused as many times as needed to copy the whole data:

byte[] data = new byte[1024];
int len = 0;
while ((len = is.read(data)) > -1) {
    os.write(data, 0, len);
}

Another consideration would be to move the whole copy operation to a separate thread (e.g. using AsyncTask) as not to block the UI thread. See the example here: http://developer.android.com/reference/android/os/AsyncTask.html

The file is File object that you want to write to.

BTW I will suggest to go for Apache Commons IO for doing file operations.

Refer -> this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top