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
Solution 1:
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:
classSavePhotoTaskextendsAsyncTask<byte[], String, String> {
@OverrideprotectedStringdoInBackground(byte[]... jpeg) {
File photo=newFile(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=newFileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
Solution 2:
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);
}
}
Solution 3:
Hey this codes for kotlin
camera.addCameraListener(object : CameraListener(){
overridefunonPictureTaken(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)
}
}
})
Solution 4:
Here's the function to convert byte[] into image.jpg
publicvoidSavePhotoTask(byte [] jpeg){
FileimagesFolder=newFile(Environment.getExternalStorageDirectory(), "Life Lapse");
imagesFolder.mkdirs();
final File photo= newFile(imagesFolder, "name.jpg");
try
{
FileOutputStream fos=newFileOutputStream(photo.getPath());
fos.write(jpeg);
fos.close();
}
catch(Exception e)
{
}
}
Post a Comment for "Android/java: Saving A Byte Array To A File (.jpeg)"