Android: Saving Bitmap to External Memory - android

I'm currently working on a project of capturing an image, cropping the image, processing the image then saving the processed image. My problem lies in saving the processed image. I can't save the processed image. For every image that is captured, the captured image is being shown in the gallery instead of the processed image. I'm thinking that because the capturing image code saves the image to the SD card, I can't save the processed image that is on a bitmap... I hope you can enlighten me on what is the problem of my code. There is no error on the code by the way.
To be a little more specific, the app I'm working with captures image then crops the image. After that image will be shown in imageView. When processed, it will be again shown in an imageView. when i get the image to save in the external storage, nothing happens...
Here is the code for capturing and cropping the image
public class MainActivity extends Activity {
ImageView mainImageview;
Button mainButtonTakePhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeControls();
}
private void initializeControls() {
mainImageview = (ImageView)findViewById(R.id.imageView1);
mainButtonTakePhoto = (Button)findViewById(R.id.button3);
mainButtonTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
/* create an instance of intent
* pass action android.media.action.IMAGE_CAPTURE
* as argument to launch camera */
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
/*create instance of File with name img.jpg*/
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
/*put uri as extra in intent object*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if request code is same we pass as argument in startActivityForResult
if(requestCode==1){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
if(requestCode==2){
//Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//set image bitmap to image view
mainImageview.setImageBitmap(thePic);
}
}
//create helping method cropCapturedImage(Uri picUri)
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
//indicate output X and Y
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 2);
}
}
And here is the code for saving the image.
public void saveImageToExternalStorage(Bitmap finalBitmap) {
String root =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file1 = new File(myDir, fname);
if (file1.exists())
file1.delete();
try {
FileOutputStream out = new FileOutputStream(file1);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file1.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
Thanks a lot for your help. I'm trying not to trouble anyone if this is a stupid question. And I'm really trying my best to research and study every part of the code I'm using/lifting... Thanks again...

Are you testing it on api23 and up? If so... are you manually requesting permission to WRITE_EXTERNAL_STORAGE? because putting it in manifest is not enough.

The code works just fine... I'm sorry to waste all of your time and concern...
I just added the manifest to write to memory...
When I read from android developers about the manifest for writing to storage, I thought there is no need for the manifest when you are using API19 and up...

Related

Android Bitmap.Compress saves image of Low Quality and Scaled down image

I am trying to make an app that takes a picture and embed another image like a logo onto the original image. But I have a problem in the initial stages.
I am trying to save the image from the Bitmap received from onActivityResult for the camera intent. But after using the following code, the images are scaled-down and compressed too much and looks bad. Can someone help me retain the picture quality and size?
Here are the pictures that the app saved:
public void saveBitmapToGallery(Bitmap bm,String picturename){
String root = Environment.getExternalStorageDirectory().toString();
File mydir = new File(picturepath);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
displayheight = dm.heightPixels;
displaywidth = dm.widthPixels;
File file = new File(mydir, picturename+".JPG");
try {
FileOutputStream fos = new FileOutputStream(file);
bm.createScaledBitmap(bm,displaywidth,displayheight,true);
bm.compress(Bitmap.CompressFormat.JPEG,100, fos);
fos.flush();
fos.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
I expect an image like the general camera app so that I can work on embedding the logo once I can get my app to save good quality images.
the image did not convert into byte output
also, Go for My Github Profile for this
https://github.com/axarlotwala/CafeDelearenter code here
// using intent open file chooser option
private void ShowFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
// show selected and path image in imageview
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
PATH = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),PATH);
cat_image.setImageBitmap(bitmap);
tv_path.setText("Path : " .concat(GetPath(PATH)));
} catch (IOException e) {
e.printStackTrace();
}
}
//get correct path of image
private String GetPath(Uri uri){
String result;
Cursor cursor = getActivity().getContentResolver().query(uri,null,null,null,null);
if (cursor == null){
result = uri.getPath();
}else {
cursor.moveToFirst();
int id = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
result = cursor.getString(id);
cursor.close();
}
return result;
}
Well, I figured out what was wrong with the output image. We need to use EXTRA_OUTPUT for the picture to be saved in full size, otherwise only a thumbnail is saved.
Here is what we need to to before starting camera activity for result
if (picturefile != null) {
Uri pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() +
".provider", picturefile);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri); //This makes the image to save in full rather than just a low quality scaled-down thumbnail.
}
startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);

Cropped image not working with tess-two

I am creating an app that can capture image through camera and can extract the text in the image using tess-two library of android.
The code works fine until I added the option of cropping the image. After cropping the image the error occurs on the line
tessbaseAPI.setImage(bitmap)
The log says
Failed to read bitmap
Below is my code for cropping the image
private void performCrop() {
// take care of exceptions
try {
Log.v(TAG, "Inside try of performCrop");
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
Log.v(TAG, "Going to onActivityResult now");
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
and for performing OCR
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Log.v(TAG, "Request Code is REQUEST_IMAGE_CAPTURE");
picUri = data.getData();
performCrop();
} else if (requestCode == CROP_PIC) {
Log.v(TAG, "Request Code is CROP_PIC");
Bundle extras = data.getExtras();
Bitmap bitmap = extras.getParcelable("data");
TextView res = (TextView) findViewById(R.id.hello);
//imageView.setImageBitmap(imageBitmap);
//Image image = ImageIO.read(imageFile);
//BufferedImage buffimg = (BufferedImage) image;
//BufferedImage img = ImageHelper.convertImageToGrayscale(buffimg);
//ITesseract instance = new Tesseract(); // JNA Interface Mapping
//ITesseract instance = new Tesseract1(); // JNA Direct Mapping
//TessDataManager.initTessTrainedData(context);
if (isStoragePermissionGranted() == true) {
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String path = Environment.getExternalStorageDirectory() + "/";
//String path = "/mnt/sdcard/";
tessBaseAPI.setDebug(true);
tessBaseAPI.init(path, "eng");
tessBaseAPI.setImage(bitmap);
String text = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
res.setText(text);
}
}} else {
TextView res = (TextView) findViewById(R.id.hello);
res.setText("Well damn");
}
}
}
A line from log
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.abc.snaptravel/com.example.abc.snaptravel.MainActivity}: java.lang.RuntimeException: Failed to read bitmap
I will appreciate any help. Thank you!
Well there were a LOT of problems that were coming up. Overall I think the main problem was that I wasn't able to access my SD card. I read somewhere that it is tough to access SD cards in HTC models and I was using an HTC model only.
I solved the problem by saving my cropped image in the internal memory and then giving that path to the tessbaseAPI.setImage(File file)
The crop function became this -
private void performCrop() {
// take care of exceptions
try {
Log.v(TAG, "Inside try of performCrop");
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpg");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
// retrieve data on return
cropIntent.putExtra("return-data", false);
// start the activity - we handle returning in onActivityResult
Log.v(TAG, "Going to onActivityResult now");
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
and the onActivityResult() became this -
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Log.v(TAG, "Request Code is REQUEST_IMAGE_CAPTURE");
picUri = data.getData();
performCrop();
} else if (requestCode == CROP_PIC) {
Log.v(TAG, "Request Code is CROP_PIC");
Bundle extras = data.getExtras();
//Bitmap bitmap = (Bitmap)extras.get("data");
TextView res = (TextView) findViewById(R.id.hello);
ImageView im = (ImageView)findViewById(R.id.imageView);
//im.setImageBitmap(bitmap);
//imageView.setImageBitmap(imageBitmap);
//Image image = ImageIO.read(imageFile);
//BufferedImage buffimg = (BufferedImage) image;
//BufferedImage img = ImageHelper.convertImageToGrayscale(buffimg);
//ITesseract instance = new Tesseract(); // JNA Interface Mapping
//ITesseract instance = new Tesseract1(); // JNA Direct Mapping
//TessDataManager.initTessTrainedData(context);
if (isStoragePermissionGranted() == true) {
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String path = Environment.getExternalStorageDirectory() + "/";
//String path = "/mnt/sdcard/";
tessBaseAPI.setDebug(true);
tessBaseAPI.init(path, "eng");
File file = new File(picUri.getPath());
tessBaseAPI.setImage(output);
String text = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
res.setText(text);
}
}} else {
TextView res = (TextView) findViewById(R.id.hello);
res.setText("Well damn");
}
}
}
Note that I have done this -
cropIntent.putExtra("return-data", false);
We don't need data from this function when we are providing the file it is stored in.

Android saving PNG from the device camera (Poor quality)

I am having a problem while trying to save a photo to storage with an Android app. The app uses the devices camera to take a photo and save it as a PNG to the device.
For some reason no matter what I do or where I store the image the quality is very poor. The app is an existing project that is quite large so I was wondering if there are other factors to consider when saving images to a device or maybe another way of overriding the quality.
This is the function that was coded by the previous dev:
public String saveImageToDevice(Bitmap image) {
saveCanvasImage(image);
String root = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.app.android";
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = "Image-"+ timeStamp +".png";
File file = new File (myDir, fname);
if (file.exists ()){
file.delete ();
}
try {
Toast.makeText(getActivity(), "Saving Image...", Toast.LENGTH_SHORT).show();
Log.i("Image saved", root+"/saved_images/"+fname);
FileOutputStream out = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, out);
imageLocations.add(fname);
out.flush();
out.close();
//return myDir.getAbsolutePath() + "/" +fname;
return fname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
And this is a function I have tried myself from an example online:
public void saveCanvasImage(Bitmap b) {
File f = new File(Environment.getExternalStorageDirectory().toString() + "/img.png");
try {
f.createNewFile(); // your mistake was at here
FileOutputStream fos = new FileOutputStream(f);
b.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
Both of these produce the same very poor images. I have posted a before and after segment below.
This is what the camera preview looks like.
This is the resulting image once it has saved.
After speaking to a few people i am including my camera intent code:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
// Define the file-name to save photo taken by Camera activity
String fileName = "Camera_Example.png";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
#SuppressWarnings("unused")
Uri imageUri = getActivity().getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
//intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
As you can see the EXTRA_OUTPUT line is has been commented out due to it causing crashes with the below error:
12-17 13:31:37.339: E/AndroidRuntime(16123): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {}: java.lang.NullPointerException
I have also included my onActivityresult code too:
public void onActivityResult( int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
Bitmap bp = (Bitmap) data.getExtras().get("data");
//add the image to the note through a function call
note.addImage(bp);
note.saveImageToDevice(bp);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
OK so after a lot of help from MelquiadesI have eventually solved this issue. The problem I had was that my intent and onActivityResult were retrieving the thumbnail of the image and scaling it up (hence the poor quality).
The line below is responsible for getting the thumbnail preview (120px x 160px):
Bitmap bp = (Bitmap) data.getExtras().get("data");
In order to access the full image I need to add EXTRA_OUTPUT to the intent which looks as follows:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
I also declared my imageFilePath as a string at the top of my activity:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";
I then had to change onActivityResult so it could access the full image to use:
public void onActivityResult( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
//add the image to the note through a function call
note.addImage(rotatedBitmap);
note.saveImageToDevice(rotatedBitmap);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
The key part here is:
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
This code decodes the image you saved at imageFilePath into a usable bitmap. From here you can use it as normal.
Sometimes (apparently this is quite common) the image comes in rotated by 90°, the next bit of code will rotate that back if you need it to:
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);

How to put a date watermarker in android camera activity

I'm getting pictures with the next code:
public void foto(View v) {
nom_foto = Environment.getExternalStorageDirectory()+ aptr.ruta_temp + cuadrilla + "/" + medidor + "_"+ cont_foto + ".jpg";
File arch = new File(Environment.getExternalStorageDirectory()+ aptr.ruta_temp+ cuadrilla);
if (!arch.exists())
arch.mkdirs();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
int code = TAKE_PICTURE;
Uri output = Uri.fromFile(new File(nom_foto));
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, code);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
ImageView iv = (ImageView) findViewById(R.id.minifoto);
if (resultCode == RESULT_OK) {
new MediaScannerConnectionClient() {
private MediaScannerConnection msc = null;
{
msc = new MediaScannerConnection(getApplicationContext(), this);
msc.connect();
}
public void onMediaScannerConnected() {msc.scanFile(nom_foto,null);
}
public void onScanCompleted(String path, Uri uri)
{ msc.disconnect();}};
Toast.makeText(usuario_lectura.this,"Foto N° " + cont_foto + " agregada correctamente", Toast.LENGTH_LONG).show();
cont_foto++;
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(BitmapFactory.decodeFile(nom_foto));
}
}
if (resultCode == RESULT_CANCELED) {
File file = new File(nom_foto);
if (file.exists())
file.delete();
}
}
}
Everything works properly, the picture has taken correctly and saved on the SD card... But, I have to add a watermarker, including the date... How can I add it?, the camera activity doesn't give me these option...
In order to add a textual or graphical watermark to your image from the camera, you must open the image, edit it in a Canvas with Paint/Graphics overlays, then re-encode it as a .jpg image, and re-save it as a file on the SD card. You can save over the original file from the camera. All of these steps are fairly straightforward.
There is, however, a serious hurdle.
Most devices will not be able to open the full-size image from the camera in a single Bitmap. There is not enough heap memory available. Therefore, you will have to use a scale factor inSampleSize to open your image. Thus, the watermarked image will be forever smaller by some factor than the original from the camera.
I do not think there is any way around this issue :(

android picture from camera being taken at a really small size

Im trying to capture an image from the camera, compress it, then store it to the SD card. If I directly save it to the SD card using the code directly below, I get the full image. But if i try and load the image in the system, i get a super small image size such as 320 by 240 instead of a full 5 mp image.
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(intent, CAMERA_PIC_REQUEST);
where getImageURI() is
private Uri getImageUri() {
// Store image in dcim
file = new File(Environment.getExternalStorageDirectory() + "/DCIM","itshelp.jpg");
imgUri = Uri.fromFile(file);
file.deleteOnExit();
Log.e("syS","file is at "+imgUri);
return imgUri;
}
Now when i try to save it to internal memory instead, I use the following code that gets me the tiny image:
public void imageFromCamera() { //code to retrieve image
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
and in my startActivitForResult I have the following:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap bm = (Bitmap) data.getExtras().get("data");
Log.e("sys", "width is "+bm.getWidth()); //im gettting an extremely small width here
OutputStream outStream = null;
file = new File(Environment.getExternalStorageDirectory() + "/DCIM","itshelp.png");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 70, outStream);
outStream.flush();
outStream.close();
Log.i("Hub", "OK, Image Saved to SD");
Log.i("Hub", "height = "+ bm.getHeight() + ", width = " + bm.getWidth());
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: "+ e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: "+ e.toString());
}
}
When you call the camera intent without MediaStore.EXTRA_OUTPUT, the camera returns only a small thumbnail since the intent bundle is not designed to pass large memory blocks.
From the SDK documentation for MediaStore:
Standard Intent action that can be sent to have the camera application capture an image and return it.
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.

Categories

Resources