Search code examples
androiddrawablegalleria

Eclipse: save image from drawable resource


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 .


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" />