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.
Related
I'm trying to save bitmap to gallery to open it again from ImagePicker intent.
The problem is - if I'm saving it on external storage, it will not work on devices without it, and when I'm writing it on internal storage - it won't shown in gallery, so i can not pick that image.
Tried so many ways of resolving it, but no success this far.
I mean, is it possible to save bitmap in internal storage and open it from activity, which called to choose image from gallery?
edit: added code
private String saveToInternalStorage(Bitmap bitmapImage, String filename){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,filename + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
With that procedure it's seems like saving bitmap is ok, but i can't find that file in gallery.
When i'm trying to save an image at some devices the app crashes.
After some research i think the problem is the imageRoot, but i'm kind of lost with so many solutions...
I think the problem is about obtaining external storage path.
The device i'm using to test my app doesn't have any sd card, the path is /mnt/sdcard/Pictures and the image is being saved successfully.
I want it to work whether phone has an sd card or not.
Thanks for any help in advance.
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
private void saveImage() {
Bitmap bitmap = sqimage.getDrawingCache();
File image = new File(imageRoot, imageName);
if (image.exists()) {
image.delete();
}
try {
FileOutputStream output = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
new SingleMediaFileConnector(getActivity().getApplicationContext(), image);
} catch (FileNotFoundException e) {
e.printStackTrace();
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
}
}
Sometimes getExternalStoragePublicDirectory path doesn't exist. You need to check for its existence.
try {
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
File image = new File(imageRoot, imageName);
// Make sure the Pictures directory exists.
imageRoot.mkdirs();
// Other stuffs here
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
See here for more details.
[Edit]
An alternate way can be use:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
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.
The idea of my app is to capture image from camera then crop specified area from it.
The problem :
When i save the cropped image in my sd card for the first time to launch the app, it saved properly. but when run my app one more time and take image then crop it. when save it the first image that take and crop at first time appear in the sd card not the current one.
This is my code for save images:
public static void save(Activity activity, Bitmap bm, String name) {
OutputStream outStream = null;
File externalFilesDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File outFile = new File(externalFilesDir, "IDOCR" + File.separator + "Numbers");
if (!outFile.exists())
outFile.mkdirs();
File number = new File(outFile, name + ".PNG");
//if (number.exists())
// number.delete();
try {
//outStream = new FileOutputStream(new File(path));
outStream = new FileOutputStream(number);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
bm.recycle();
System.gc();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Maybe if you are trying to overwrite the previous version of the file, you should first delete the previous one...
You can add:
if (!outFile.exists())
outFile.mkdirs();
else {
outFile.delete();
outFile.createNewFile();
}
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)
{
}
}