The method write(byte[]) in the type FileOutputStream is not applicable for the arguments (Drawable)


Ask by : user1409172 November 03, 2012 17:59

Im attempting to save the actual image from my applications resources to a file on the SD card so it is accessible by the messaging application but I'm getting the error of - The method write(byte[]) in the type FileOutputStream is not applicable for the arguments (Drawable) - where its supposed to save it. I believe that I'm not using the appropriate method to save the actual image itself and I'm having difficulty finding a solution.

                        // Selected image id
                int position = data.getExtras().getInt("id");
                ImageAdapter imageAdapter = new ImageAdapter(this);
                ChosenImageView.setImageResource(imageAdapter.mThumbIds[position]);
                Resources res = getResources();
                Drawable drawable = res.getDrawable(imageAdapter.mThumbIds[position]); //(imageAdapter.mThumbIds[position]) is the resource ID
                try {
                    File file = new File(dataFile, FILENAME);
                    file.mkdirs();
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(drawable); // supposed to save the image here, getting the error at fos.write
                    fos.close();
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
              }
            }
        }    
View original question

Answer by : FrankNovember 03, 2012 17:59

You error does explain it all, A fileOuputStream can not take a Drawable, it needs a byte array.

So you need to get the bytes from your Drawable.

try:

Drawable drawable = res.getDrawable(imageAdapter.mThumbIds[position]);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();

....

fos.write(bitmapdata);

And while you are at it, put the fos.close() in the Finally bock

View original answer