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

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. 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);    }}


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);    }}


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)            }        }})