Cropped image not working with tess-two - android

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.

Related

In android how to Resize and user crop image before uploading image as profile pic

I am beginner in Android, I searched a lot for user cropping image before uploading the image like in whattsapp and also minimise the size of the image interms of bytes, but i am not getting any reliable answer to add in my app
There is two ways to do it . first is to provide a cropper for it and second is you can resize bitmap and then send it to server . In second case user will not know which part of image (probably center) is cropped and uploaded as his/her profile picture . So i will recommend the first one cause in that way user will know which part of image is going to truncate.
You must know that its hard to use in-build android crop app intent as it shows different behavior in different devices .So you must use third party Crop library for it of you can create your own cropper. Here are some useful Crop libraries that you can use. There are a bunch of libraries for it on github you can look for for them .
CropImageView
Crop
Crop2
public class Crop extends AppCompatActivity {
private Uri picUri;
File f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_crop);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button btn_camera = (Button) findViewById(R.id.btn_camera);
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
f = new File(android.os.Environment.getExternalStorageDirectory(), "makegifimage.jpg");
picUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(intent, 1);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(getApplicationContext(),"couldnt open your camera",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
CropImage();
} else if (requestCode == 2) {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
ImageView im_crop = (ImageView) findViewById(R.id.im_crop);
im_crop.setImageBitmap(bitmap);
}
}
}
private void CropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device is not supportting the crop action", Toast.LENGTH_SHORT);
}
}
}
and add the button and imageview to your layout
<ImageView
android:id="#+id/im_crop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<Button
android:id="#+id/btn_camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Camera"
android:layout_alignParentBottom="true" />

Android: Saving Bitmap to External Memory

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...

refactor performCrop() method out of activity class

I have a PerformCrop method which works perfectly.
I want to move it to my 'util' class so i can call it in other activities. There are complications to this in that it uses intents which return to the calling class. I think this should be no issue but maybe i'm incorrect.
Here is what i have tried and the issue i am seeing
I cut and paste performCrop() to my util class.
I had an error at 'startActivityForResult(cropIntent, CROP_IMAGE);' where it didnt recognise the method so i extended the class with 'Extends Activity'
When it runs it errors and im not 100% sure why but an exception is caught
'java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference'
Here is the method, below that is the 'onActivityResult' method. Can anyone tell me how to move the performCrop() to a non Activity extended class?
Code
public void performCrop(Uri picUri)
{
final int CROP_IMAGE = 2;
/*
* PERFORM CROP
* this must take into account he fact we may not have a crop method on phone, or the diff ways diff OS crop
*/
//NEXUS 5 OS 5 is example of this branch
// take care of exceptions
try {
// 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", 1);
cropIntent.putExtra("aspectY", 1);
// // // indicate output X and Y
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
}
// 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! Exception: " + anfe.toString(),Toast.LENGTH_SHORT);
toast.show();
}
catch (OutOfMemoryError e)
{//NOT TESTED AS HW DOES NOT GO HERE
System.out.println("out of memory");
}
catch (Exception e)
{ //NOT TESTED AS HW DOES NOT GO HERE
Display display = this.getWindowManager().getDefaultDisplay();
Point size = new Point();
//display.getSize(size);
int width = size.x;
int height = size.y;
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", width);
cropIntent.putExtra("outputY", 200);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
}
}
Called from Activity when the camera intent returns successful result. Note the crop intent will also retun to this method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
if (resultCode==RESULT_OK )
{
if(requestCode == CAMERA_IMAGE) //reply from camera
{
toolbox.performCrop(uri); //crop the picture
}
if(requestCode == CROP_IMAGE) //reply from crop
{
/* Bitmap bmp = getBitmap(uri);
imgView.setImageBitmap(bmp);*/
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bmp = extras.getParcelable("data");
imgViewProfilePic.setImageBitmap(bmp);
}
}
if (requestCode == PICK_IMAGE_FROM_GALLERY) //reply from gallery
{
Uri selectedImage = data.getData();
uri = data.getData();
toolbox.performCrop(uri);
}
}
}
Create A Class name CropImage, put your method performCrop() in it and call it from wherever you want as,
CropImage cropImage = new CropImage(this);
cropImage.performCrop(uri);
The CropImage claas would look like,
public class CropImage {
Context context;
public CropImage(Context context) {
this.context = context;
}
public void performCrop(Uri picUri)
{
final int CROP_IMAGE = 2;
/*
* PERFORM CROP
* this must take into account he fact we may not have a crop method on phone, or the diff ways diff OS crop
*/
//NEXUS 5 OS 5 is example of this branch
// take care of exceptions
try {
// 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", 1);
cropIntent.putExtra("aspectY", 1);
// // // indicate output X and Y
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
((Activity)context).startActivityForResult(cropIntent, CROP_IMAGE);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe)
{
Toast toast = Toast.makeText(context,"This device doesn't support the crop action! Exception: " + anfe.toString(), Toast.LENGTH_SHORT);
toast.show();
}
catch (OutOfMemoryError e)
{//NOT TESTED AS HW DOES NOT GO HERE
System.out.println("out of memory");
}
catch (Exception e)
{ //NOT TESTED AS HW DOES NOT GO HERE
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
Point size = new Point();
//display.getSize(size);
int width = size.x;
int height = size.y;
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", width);
cropIntent.putExtra("outputY", 200);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
((Activity)context).startActivityForResult(cropIntent, CROP_IMAGE);
}
}
}
First You Check The Where Result Going
ifgetpaternt==null)
{
Startactivityforreslt(your intent,code);
}
else
{
getpaprent().Startactivityforreslt(your intent,code);
}
If Getpaprent() method call Then result send to parent activity .
so get result in parent activity and resend to your activity .....

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

Crop an Image by passing the image file path in Android

I have tried the below code. However, it always results the 160*160 dimension image.
try {
//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(Uri.fromFile(pictureFile), "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 100);
cropIntent.putExtra("aspectY", 100);
cropIntent.putExtra("scale", true);
//indicate output X and Y
cropIntent.putExtra("outputX", 500);
cropIntent.putExtra("outputY", 500);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
} catch(ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
I would like to crop an image by passing its path.
I don't want to capture/pick from default camera app or gallery. Please help me on this.
I have solved this by create a new file before calling Intent and passing this file path to store the cropped image through intent. Here is the solution for this.
private Uri mCropImagedUri;
private final int CROP_IMAGE = 100;//unique request code number. Which is used to identify the request result in onActivityResult()
/**Crop the image
* #return returns <tt>true</tt> if crop supports by the device,otherwise false*/
private boolean performCropImage(){
try {
if(mFinalImageUri!=null){
//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(mFinalImageUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("scale", true);
//indicate output X and Y
cropIntent.putExtra("outputX", 500);
cropIntent.putExtra("outputY", 500);
//retrieve data on return
cropIntent.putExtra("return-data", false);
File f = createNewFile("CROP_");
try {
f.createNewFile();
} catch (IOException ex) {
VLLog.e("io", ex.getMessage());
}
mCropImagedUri = Uri.fromFile(f);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCropImagedUri);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
return true;
}
}
catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
return false;
}
return false;
}
private File createNewFile(String prefix){
if(prefix==null || "".equalsIgnoreCase(prefix)){
prefix="IMG_";
}
File newDirectory = new File(Environment.getExternalStorageDirectory()+"/mypics/");
if(!newDirectory.exists()){
if(newDirectory.mkdir()){
VLLog.d(mContext.getClass().getName(), newDirectory.getAbsolutePath()+" directory created");
}
}
File file = new File(newDirectory,(prefix+System.currentTimeMillis()+".jpg"));
if(file.exists()){
//this wont be executed
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
So here we should not bother about the data which comes in onActivityResult() method.
Here is the complete information about cropping image. I have used this to solve.
http://www.androidworks.com/crop_large_photos_with_android
Android doesn't support a cropping intent built in. You should not assume it's available.
Instead you should use your own solution, or use a third party library, like this one:
https://github.com/ArthurHub/Android-Image-Cropper
Read more about it here:
https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html
In this way,you can scale the image:
Bitmap.createScaledBitmap(bitmap,50,50,true);

Categories

Resources