Android/Java: Saving a byte array to a file (.jpeg)

I am developing an application for Android, and part of the application has to takes pictures and save them to the SDcard. The onPictureTaken method returned a byte array with the data of the captured image.

All I need to do is save the byte array into a .jpeg image file. I have attempted to do this with the help of BitmapFactory.decodeByteArray (to get a Bitmap) and then bImage.compress (to an OutputStream), a plain OutputStream, and a BufferedOutputStream. All three of these methods seem to give me the same weird bug. My Android phone (8MP camera and a decent processor), seems to save the photo (size looks correct), but in a corrupted way (the image is sliced and each slice is shifted; or I just get almost horizontal lines of various colors); and The weird thing is, that an Android tablet with a 5MP camera and a fast processor, seems to save the image correctly.

So I thought maybe the processor can't keep up with saving large images, because I got OutOfMemory Exceptions after about 3 pictures (even at compression quality of 40). But then how does the built in Camera app do it, and much faster too? I'm pretty sure (from debug) that the OutputStream writes all the data (bytes) and it should be fine, but it's still corrupted.

***In short, what is the best/fastest way (that works) to save a byte array to a jpeg file?

Thanks in advance, Mark

code I've tried (and some other slight variations):

    try {
        Bitmap image = BitmapFactory.decodeByteArray(args, 0, args.length);
        OutputStream fOut = new FileOutputStream(externalStorageFile);
        long time = System.currentTimeMillis();
        image.compress(Bitmap.CompressFormat.JPEG,
                jpegQuality, fOut);
        System.out.println(System.currentTimeMillis() - time);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
    }

and

    try {
        externalStorageFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(externalStorageFile);
        fos.write(args);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

All I need to do is save the byte array into a .jpeg image file.

Just write it out to a file. It already is in JPEG format. Here is a sample application demonstrating this. Here is the key piece of code:

class SavePhotoTask extends AsyncTask<byte[], String, String> {
    @Override
    protected String doInBackground(byte[]... jpeg) {
      File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");

      if (photo.exists()) {
            photo.delete();
      }

      try {
        FileOutputStream fos=new FileOutputStream(photo.getPath());

        fos.write(jpeg[0]);
        fos.close();
      }
      catch (java.io.IOException e) {
        Log.e("PictureDemo", "Exception in photoCallback", e);
      }

      return(null);
    }
}

Save byte array of image to file, You can try this. public writeToFile(byte[] array) { try { String path = ""; FileOutputStream stream = new FileOutputStream(path); stream.write(array); } catch  I am developing an application for Android, and part of the application has to takes pictures and save them to the SDcard. The onPictureTaken method returned a byte array with the data of the captured image. All I need to do is save the byte array into a .jpeg image file.

This Code is perfect for saving image in storage, from byte[]... note that "image" here is byte[]....taken as "byte[] image" as a parameter into a function.

    File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");

    if (photo.exists()) {
        photo.delete();
    }

    try {
        FileOutputStream fos=new FileOutputStream(photo.getPath());
        Toast.makeText(this, photo.getPath(), Toast.LENGTH_SHORT).show();
        fos.write(image);
        fos.close();
    }
    catch (java.io.IOException e) {
        Log.e("PictureDemo", "Exception in photoCallback", e);
    }
}

bytearray - Android/Java: Saving a byte array to a file (.jpeg), All I need to do is save the byte array into a .jpeg image file. Just write it out to a file. It already is in JPEG format. Here is a sample application demonstrating this. Use Directory.CreateDirectory to create your folder in the public Picture directory and FileOutputStream to write your byte[] to a file. Example: byte[] reducedImage = `some jpeg-based byte array` var filename = System.IO.Path.Combine(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures).ToString(), "NewFolder"); Directory.CreateDirectory(filename); filename = System.IO.Path.Combine(filename, "filename.jpg"); using (var fileOutputStream = new FileOutputStream(filename

Hey this codes for kotlin

camera.addCameraListener(object : CameraListener(){

        override fun onPictureTaken(result: PictureResult) {
            val jpeg = result.data //result.data is a ByteArray!
            val photo = File(Environment.getExternalStorageDirectory(), "/DCIM/androidify.jpg");
            if (photo.exists()) {
                photo.delete();
            }
            try {
                val fos = FileOutputStream(photo.getPath() );
                fos.write(jpeg);
                fos.close();
            }
            catch (e: IOException) {
                Log.e("PictureDemo", "Exception in photoCallback", e)
            }
        }
})

Android saving files in internal storage, In my example I will try to save received image in data/data/​YOUR_APP_PACKAGE/files/MyAppName/Images/image.jpeg. The problem appears when we want  Java provides ImageIO class for reading and writing an image. To convert an image to a byte array – Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class.

How to convert Byte Array to Image in java?, How to convert Byte Array to Image in java? Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the Java provides ImageIO class for reading and writing an image. To convert a byte array to an image. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).

Java: convert image to byte array, convert byte , First of all, the byte type in Java is an 8-bit signed two's complement integer. How to convert byte array back to an image file? android doubt, ios question, sql query, sqlite query, nodejsquery, dns query() on face recognition so i want to convert the image of jpeg form to pgm form in java..so can you please help us sir… I have a file saved in disk encrypted and unlock the encryption so i got the array of bytes so i want to convert them to file to show the pdf file in pdf viewer but without saving the file in disk without encryption – farajnew Jul 26 '11 at 11:21

Java: convert a file to a byte array, then convert byte array to a file., To convert a file to byte array, ByteArrayOutputStream class is used. This class implements an output To convert byte array back to the original file, FileOutputStream class is used. A file output stream is an getLogger(genJpeg.​class. I want to do the same (with Android)… have you found any way?? dddddddd. NOOB. I am developing an application for Android, and part of the application has to takes pictures and save them to the SDcard. The onPictureTaken method returned a byte array with the data of the captured image. All I need to do is save the byte array into a .jpeg image file.

Comments
  • have you tried doing this : stackoverflow.com/questions/4263375/…
  • I think this might be my exact problem: stackoverflow.com/questions/5859876/… It's not on the desire, but also on an HTC phone
  • Yeah, I tried what they did and it seems to be the problem. Now how to fix it... Anyone know how to fix it? Because apps like Paper Camera and Camera ZOOM FX have working preview (they don't distort) and take pictures fine. If not, I guess I either have to have the camera preview distorted, but pictures work; or have the preview look nice, and have it not work on some HTC devices...
  • This does answer my question, so I will pick it. But if you looked in the comments, I discovered that the problem was not in saving, but that some HTC devices seem to corrupt images when you use "parameters.setPreviewSize" Do you know how to work around or with that bug? Because if I don't set an optimal preview size, then the preview becomes squished and looks a bit weird.
  • @Mark: No clue. You might consider posting a fresh question on that topic.
  • @CommonsWare i have used your code but i am getting corrupt image file.That means i cann't open file.
  • I almost got fooled by fos.write(jpeg[0]); which writes only one byte in the File. In this code, you should write fos.write( jpeg ); to have the whole byte array written.
  • @TheSunshinator: No. jpeg is byte[]..., so jpeg[0] is a byte[].