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

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

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

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

Here's the function to convert byte[] into image.jpg
public void SavePhotoTask(byte [] jpeg){
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Life Lapse");
imagesFolder.mkdirs();
final File photo= new File(imagesFolder, "name.jpg");
try
{
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg);
fos.close();
}
catch(Exception e)
{
}
}

Related

Why is image corrupted after 2-3 times byte array to image conversion?

I am writing bytes to jpg image, but after writing bytes, whenever I am trying to open that image from ES file explorer, image gets corrupted.
Below is the code I am trying:
private void overWriteImage() {
if (file.exists()) {
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
fos.write(this.imageBytes);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}

Bitmaps and out of memory error

I am trying to save many bitmaps in my app's folder on sdcard. However I am getting out of memory error. What is the best way to handle bitmaps and memory in this situation. Also where will I call bitmap.recycle() looking at below code? Thanks
Here is the code with which I am saving bitmaps on sdcard
Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.sky);
ByteArrayOutputStream bStream1 = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.PNG, 100, bStream1);
File file= new File(Environment.getExternalStorageDirectory() + File.separator + "AppName" + "/image1.png");
if(!file.exists()) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bStream1.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I think to use bitmap.recycle() and keep your code nice, you should move if(!file.exists()) into try statement, and then in finally recycle your Bitmap
try {
if(!file.exists()) {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bStream1.toByteArray());
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
b1.recycle()
}
Something like this.

What is the phone storage in Android devices?

I can pass sdcard location to my adb command using
file:///sdcard/Android/screen.bmp
What is the equivalent string, if my file is saved in phone memory instead of sdcard, will it be
file:///phone/Android/screen.bmp
That isn't necessarily how you access things saved internally on your phone.
Keep in mind how you save an image to internal storage:
Bitmap bitmap = ______; //get your bitmap however
try {
FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
Log.e("Saving the bitmap",e.getMessage());
}
Now, to go read it, we just get the context, and call getFileStreamPath(filename) on it.
Bitmap retrievedImage;
String filename = "desiredFilename.png";
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
retrievedImage = BitmapFactory.decodeStream(fi);
} catch (Exception e) {
Log.e("Retrieving the image", e.getMessage());
}
You can read more about this here.

can't save file in android file system

I'm trying to capture a photo with the camera and save it (to be previewed later) and it seems to work with the emulator but when I use it on my GalaxyS - it doesn't save the file (I use RootExplorer to check) and there's no preview.
What am I doing wrong?
Code for saving the file:
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// Write to SD Card
String filename = "captured_image.jpg";
Log.d("##--File name--##", filename);
outStream = openFileOutput(filename, Context.MODE_WORLD_READABLE); // <9>
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) { // <10>
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
Code for displaying:
ImageView imagePrev = (ImageView) findViewById(R.id.image_capturedimagepreview_preview);
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(openFileInput("captured_image.jpg"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imagePrev.setImageBitmap(bmp);
i think i found the problem.
instead of outStream = openFileOutput(filename, Context.MODE_WORLD_READABLE); i should use outStream = getApplicationContext().openFileOutput(filename, Context.MODE_WORLD_READABLE);
but now i'm facing a new one - the file seems to be corrupted cause when i open it with the Android's viewer it's just black and its size is always 18474 bytes.
any ideas?
Where are you storing the image? Have you tried using an absolute path? Do you have the read/write external permission in the manifest?
I used something like this in my program to store an image in a directory the same as my package name.
File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName() );
File imagePath = new File(path,"capture_image.jpg");
EDIT:
If its your first time using the sd card for your given package name you will need to create the directory before trying to write to it.

Store and retrieve images into sdcard

I have a set of image urls. I download it to bitmap. Now I want to store these images into sdcard/project folder. If I don't have such a file, I have to create it. What I have done right now is:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, imageName);
if(!file.exists()) {
file.mkdir();
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), "file://"
+ file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I am not getting images inserted into sdcard. What is wrong in my code? Please reply. Thanks in advance.
Try using the below code:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String fileName = edtNameImage.getText().toString().trim();//this can be changed
if (fileName.equalsIgnoreCase("")) {
Toast.makeText(context, "Fields cannot be left blank",
Toast.LENGTH_SHORT).show();
return false;
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// write the bytes in file
FileOutputStream fo;
try {
file.createNewFile();
fo = new FileOutputStream(file);//snapshot image is the image to be stored.
if (snapShotImage!=null)
{
snapShotImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}else{
return false;
}
fo.write(bytes.toByteArray());
// ChartConstants.IMAGE_STORAGE++;
fo.flush();
fo.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return true;
You can also check for duplicacy in names with some additional code lines.
Let me know if it helps.
Have you made sure that the appropriate permissions for writing to/reading from an external storage device have been set in your Manifest.xml file?
Also, does the code exit with any of the exceptions above? Print more illustrative messages than the stacktrace. Something like so:
try {
} catch (FileNotFoundException e) {
Log.v(this.toString(), "Exception caught in block");
}
or something on these lines..
HTH
Sriram
Problems with your code:
1) You are creating a directory with the filename. Instead try mkdir() with only the 'path'
2) Pass only 'file.getAbsolutePath()' without the "file://" to insertImage() function
3) There is an alternate api to insertImage for which you need not create one more file locally. Pass the bitmap directly to that.
Hope this helps.

Categories

Resources