0

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 .

Gioele
  • 83
  • 1
  • 11
  • What are you going to do with the output file when you have saved it? You can use `Environment.getExternalStorageDirectory().getPath()` to get the directory location of the external storage (SDcard) on the device. You can then append any directory name that you want to create to store files into. I like to use the application's package name to avoid any conflicts. You can then create a `File` handle using `File myFile = new File( SDdirectory, "filename" );` – HeatfanJohn May 05 '13 at 18:15
  • thank but the SDdirectory give me problem :( – Gioele May 05 '13 at 21:34
  • Fyi, `String SDdirectory = Environment.getExternalStorageDirectory().getPath()` – HeatfanJohn May 06 '13 at 01:12
  • You are not writing `bitmapdata` to `OutputStream os`. After that you should call `os.close()`. I think the initial approach (http://stackoverflow.com/revisions/16387394/3) was better since now you decompress the file and compress it again, which causes unneeded CPU load. – ohaleck May 06 '13 at 18:29

3 Answers3

1

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

ohaleck
  • 661
  • 4
  • 20
1

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" />
mexok
  • 89
  • 1
  • 8
  • thanks so much but in the tipe fos can't resolve a variable,I have to do? – Gioele May 05 '13 at 21:16
  • Oh sorry, I forget this line: "FileOutputStream fos;" --> you can also put it before you call fos the first time: "FileOutputStream fos = new FileOutputStream(f);" – mexok May 06 '13 at 05:20
  • then you have the variable fos already used for something else. so just rename it. - a variable is a pointer to a specific space in your ram. if you have 2 "pointers", which point on the same space and try to do different operations, the computer will crash or do bullshit. that's why the compiler didn't build and run your program. – mexok May 06 '13 at 12:56
  • please what should I do then? – Gioele May 06 '13 at 13:48
  • rename the varible! so for example write instead of "fos" "fileoutputstream". – mexok May 06 '13 at 16:33
  • Bitmapbitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher22); File dir = new File ("/sdcard/foldername/"); File f = new File(dir, String.format("mybitmapname.png")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 , bos); byte[] bitmapdata = bos.toByteArray(); FileOutputStream fos; FileOutputStream fos = new FileOutputStream(f); fileoutputstream.write(bitmapdata); fileoutputstream.flush(); fileoutputstream.close(); fileoutputstream.close(); so sorry but give me equal error – Gioele May 06 '13 at 18:12
  • you defined it 2 times: 1. time: FileOutputStream fos; 2. time: FileOutputStream fos = new FileOutputStream(f); --- you said the compiler 2 times, that the variable fos is from type FileOutputStream - so just try with this code: – mexok May 06 '13 at 18:18
  • Bitmapbitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher2‌​2); File dir = new File ("/sdcard/foldername/"); File f = new File(dir, String.format("mybitmapname.png")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 , bos); byte[] bitmapdata = bos.toByteArray(); FileOutputStream fileoutputstream = new FileOutputStream(f); fileoutputstream.write(bitmapdata); fileoutputstream.flush(); fileoutputstream.close(); fileoutputstream.close(); bos.close(); – mexok May 06 '13 at 18:18
  • ohhhhh thanks I understand how it works and it has saved me the image of the store, but now I want to save it in the gallery please let – Gioele May 06 '13 at 18:21
  • --- I recommend you to learn the basics of java programming. There are some good tutorials out there, for example from thenewboston: http://thenewboston.org/list.php?cat=31 – mexok May 06 '13 at 18:22
  • it is already in the gallery - the gallery searches on your sdcard for photos. if you want your pictures to be in the camera folder rename the directory: "File dir = new File ("\DCIM\camera");" – mexok May 06 '13 at 18:29
  • thanks I've already seen those tutorials but I'm italian and i have some problems to understand the language anyway thank you very much – Gioele May 06 '13 at 18:30
  • np, your welcome and i know your problem. i'm from germany and had also a hard time to read english articles about programming, but you will accustom to it. – mexok May 06 '13 at 18:34
  • ah yes indeed friend listens to the image is saved in the archive because I'm using :Environment.getExternalStorageDirectory().getPath(); File externalStorageDir = Environment.getExternalStorageDirectory(); – Gioele May 06 '13 at 18:50
  • yea, but hardcoding sdcard is not the best style, because on some devices it might be a different place - there might be a function for it, but i don't know it and i'm tired of searching it on the internet, so i just hardcoded it, but if you wanna be smart you must find another solution. – mexok May 06 '13 at 19:11
0

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

Vishal Pawale
  • 3,416
  • 3
  • 28
  • 32