2

I have read an image file into ByteArray, but how can I write it back. I mean save ByteArray to image file in the file system. PNG format preferred.

My code from PNG file to ByteArray:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), mUri);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

I know there are some similar questions, but I didn't find the exact solution for this one. Thanks!!!

wwnigel
  • 497
  • 7
  • 14
  • Can you use a Bitmap image? – Huy Tran Jul 26 '14 at 01:44
  • Hi @HuyTran, I am okay to use Bitmap image, but the limitation is that the data I get is the compressed byteArray, not the original bitmap. I am okay with converting it back to bitmap then write the bitmap to file, but it doesn't work out either. – wwnigel Jul 26 '14 at 19:56

1 Answers1

5

Just use a FileOutputStream to write your byte array into. Like this:

File file = new File(getFilesDir()+"/file.png");
FileOutputStream fos = new FileOutputStream(file);

//write your byteArray here
fos.write(byteArray);
fos.flush();
fos.close();
joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
  • 1
    Hi @joao2fast4u, thank you for you answer. I tried you code and write the file.png to /Download folder, but I didn't see any file in the Download folder, nor did I see any error in LogCat. I also double checked three things, 1)I have enabled the permission of "WRITE_EXTERNAL_STORAGE" in the manifest file. 2) byteArray is not empty, it's about 70k bytes. 3) the file directory should be correct, it's "/storage/emulated/0/Download/images.jpg". Is there any other possible cause of this file writing problem? – wwnigel Jul 26 '14 at 19:50