I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.
Related
Below is My Code which is working Nic when i am using Activity but when i implemet this code in fragment then after select image from gallery or capture from camera then its not showing crop option. also my image not showing in imageView.
Below is my Camera Handler:
public class CameraHandler {
public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
CROP_GALLARY_REQUEST = 1002;
private Intent imageCaptureintent;
private boolean isActivityAvailable;
Context context;
private List<ResolveInfo> cameraList;
List<Intent> cameraIntents;
Uri outputFileUri;
Intent galleryIntent;
Uri selectedImageUri;
private String cameraImageFilePath, absoluteCameraImagePath;
Bitmap bitmap;
ImageView ivPicture;
String ivPicture1 = String.valueOf(ivPicture);
public CameraHandler(Context context) {
this.context = context;
setFileUriForCameraImage();
}
public void setIvPicture(ImageView ivPicture) {
this.ivPicture = ivPicture;
}
private void setFileUriForCameraImage() {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "image.jpg";
final File sdImageMainDirectory = new File(root, fname);
absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
}
public String getCameraImagePath() {
return cameraImageFilePath;
}
private void getActivities() {
imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = ((Activity) context)
.getPackageManager();
this.cameraList = packageManager.queryIntentActivities(
imageCaptureintent, 0);
if (cameraList.size() > 0) {
isActivityAvailable = true;
} else {
isActivityAvailable = false;
}
}
private void fillCameraActivities() {
getActivities();
if (!isActivityAvailable) {
return;
}
cameraIntents = new ArrayList<Intent>();
for (ResolveInfo resolveInfo : cameraList) {
Intent intent = new Intent(imageCaptureintent);
intent.setPackage(resolveInfo.activityInfo.packageName);
intent.setComponent(new ComponentName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name));
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
}
private void fillGallaryIntent() {
galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
}
public void showView() {
fillCameraActivities();
fillGallaryIntent();
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
((Activity) context).startActivityForResult(chooserIntent,
IMAGE_PIC_CODE);
}
private Bitmap getBitmapFromURL(String src) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(src, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 192, 256);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(src, options);
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void onResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_PIC_CODE) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.v("", "ics");
} else {
Log.v("", " not ics");
}
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
&& action != null) {
Log.v("", "action = null");
isCamera = true;
} else {
Log.v("", "action is not null");
}
}
if (isCamera) {
selectedImageUri = outputFileUri;
onResultCameraOK();
} else {
selectedImageUri = data == null ? null : data.getData();
onResultGalleryOK();
}
}
}
if (requestCode == CROP_CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfCamera(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
if (requestCode == CROP_GALLARY_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfGallary(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
}
private void doCropping(int code) {
Log.v("", this.cameraImageFilePath);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
try {
((Activity) context).startActivityForResult(cropIntent, code);
} catch (Exception e) {
}
}
private void onResultCameraOK() {
this.cameraImageFilePath = absoluteCameraImagePath;
this.bitmap = getBitmapFromURL(cameraImageFilePath);
doCropping(CROP_CAMERA_REQUEST);
}
private void onResultGalleryOK() {
this.cameraImageFilePath = selectedImageUri.toString();
this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
selectedImageUri));
doCropping(CROP_GALLARY_REQUEST);
}
private void resultOnCropOkOfCamera(Intent data) {
this.bitmap = data.getExtras().getParcelable("data");
Log.v("", "cameraImageFilePath on crop camera ok => "
+ cameraImageFilePath);
setImageProfile();
}
private void resultOnCropOkOfGallary(Intent data) {
Bundle extras2 = data.getExtras();
this.bitmap = extras2.getParcelable("data");
setImageProfile();
}
private void resultOnCroppingCancel() {
Log.v("", "do cropping cancel" + cameraImageFilePath);
setImageProfile();
}
private void setImageProfile() {
Log.v("", "cameraImagePath = > " + cameraImageFilePath);
if (ivPicture != null) {
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
String ivPicture =ConDetTenthFragment.getStringImage(bitmap);
Log.d("byte code -", ivPicture);
/*Intent i = new Intent(context, ImageUpload.class);
String getrec = ivPicture;
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("moin", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
context.startActivity(i);*/
} else {
Log.v("", "bitmap is null");
}
}
}
public String getVar1() {
return ivPicture1;
}
/*public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}*/
}
Below is my Fragment Code:
public class ConDetTenthFragment extends Fragment {
static String FileByte;
String FileName;
String resultlog;
ImageView ivProfile;
Context context = getActivity();
Button btnUpload, send;
CameraHandler cameraHandler;
private ProgressDialog pDialog;
static String abc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
/*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));*/
ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
send = (Button) rootView.findViewById(R.id.btnsend);
cameraHandler = new CameraHandler(context);
cameraHandler.setIvPicture(ivProfile);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraHandler.showView();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new async().execute();
}
});
return rootView;
}
public static ConDetTenthFragment newInstance(String text) {
ConDetTenthFragment f = new ConDetTenthFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
public static String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
abc = encodedImage;
//encodedImage = FileByte.setText().toString();
return encodedImage;
}
// Async task to perform login operation
class async extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Get the bundle
/*Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("moin");*/
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty(parameter, abc);//add the parameters
request.addProperty(parameter2, "moin.jpeg");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
// this is the actual part that will call the webservice
androidHttpTransport.call(soap_action, envelope);
// SoapPrimitive prim = (SoapPrimitive) envelope.getResponse(); // Get the SoapResult from the envelope body.
SoapObject response = (SoapObject) envelope.bodyIn;
// resultlog=prim.toString();
hideDialog();
} catch (Exception e) {
e.printStackTrace();
}
return resultlog;
}
}
/*#Override
public void onClick(View view) {
if (view == btnUpload) {
cameraHandler.showView();
}
if (view == send) {
new async().execute();
}
}*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
cameraHandler.onResult(requestCode, resultCode, data);
Log.v("", "code = > " + requestCode);
}
// this is used to show diologue
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
// this is used to hide diologue
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
I found the answer to call the image crop in a fragment use
AddImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = CropImage.activity()
.setAspectRatio(16,9)
.getIntent(getContext());
startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
on the onActivityResult you must add an extra line super.onActivityResult(requestCode, resultCode, data);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
Log.e("resultUri ->", String.valueOf(resultUri));
AddImage1.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Log.e("error ->", String.valueOf(error));
}
}
}
This worked perfectly for me
https://github.com/ArthurHub/Android-Image-Cropper/wiki/Using-built-in-CropImageActivity
You could check the official documentation, it stated how to get the cropped Uri on a fragment. Below is my code snippet.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(4,4)
//this was what I missed
.start(getContext(), this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
Log.d("resultUri ->", String.valueOf(resultUri));
imageViewProfilePicture.setImageURI(resultUri);
mImageUri = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Log.d("error", String.valueOf(error));
}
}
}
Below is my Camera Handler:
public class CameraHandler {
public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
CROP_GALLARY_REQUEST = 1002;
private Intent imageCaptureintent;
private boolean isActivityAvailable;
Context context;
private List<ResolveInfo> cameraList;
List<Intent> cameraIntents;
Uri outputFileUri;
Intent galleryIntent;
Uri selectedImageUri;
private String cameraImageFilePath, absoluteCameraImagePath;
Bitmap bitmap;
ImageView ivPicture;
String ivPicture1 = String.valueOf(ivPicture);
public CameraHandler(Context context) {
this.context = context;
setFileUriForCameraImage();
}
public void setIvPicture(ImageView ivPicture) {
this.ivPicture = ivPicture;
}
private void setFileUriForCameraImage() {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "image.jpg";
final File sdImageMainDirectory = new File(root, fname);
absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
}
public String getCameraImagePath() {
return cameraImageFilePath;
}
private void getActivities() {
imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = ((Activity) context)
.getPackageManager();
this.cameraList = packageManager.queryIntentActivities(
imageCaptureintent, 0);
if (cameraList.size() > 0) {
isActivityAvailable = true;
} else {
isActivityAvailable = false;
}
}
private void fillCameraActivities() {
getActivities();
if (!isActivityAvailable) {
return;
}
cameraIntents = new ArrayList<Intent>();
for (ResolveInfo resolveInfo : cameraList) {
Intent intent = new Intent(imageCaptureintent);
intent.setPackage(resolveInfo.activityInfo.packageName);
intent.setComponent(new ComponentName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name));
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
}
private void fillGallaryIntent() {
galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
}
public void showView() {
fillCameraActivities();
fillGallaryIntent();
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
((Activity) context).startActivityForResult(chooserIntent,
IMAGE_PIC_CODE);
}
private Bitmap getBitmapFromURL(String src) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(src, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 192, 256);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(src, options);
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void onResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_PIC_CODE) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.v("", "ics");
} else {
Log.v("", " not ics");
}
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
&& action != null) {
Log.v("", "action = null");
isCamera = true;
} else {
Log.v("", "action is not null");
}
}
if (isCamera) {
selectedImageUri = outputFileUri;
onResultCameraOK();
} else {
selectedImageUri = data == null ? null : data.getData();
onResultGalleryOK();
}
}
}
if (requestCode == CROP_CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfCamera(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
if (requestCode == CROP_GALLARY_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfGallary(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
}
private void doCropping(int code) {
Log.v("", this.cameraImageFilePath);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
try {
((Activity) context).startActivityForResult(cropIntent, code);
} catch (Exception e) {
}
}
private void onResultCameraOK() {
this.cameraImageFilePath = absoluteCameraImagePath;
this.bitmap = getBitmapFromURL(cameraImageFilePath);
doCropping(CROP_CAMERA_REQUEST);
}
private void onResultGalleryOK() {
this.cameraImageFilePath = selectedImageUri.toString();
this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
selectedImageUri));
doCropping(CROP_GALLARY_REQUEST);
}
private void resultOnCropOkOfCamera(Intent data) {
this.bitmap = data.getExtras().getParcelable("data");
Log.v("", "cameraImageFilePath on crop camera ok => "
+ cameraImageFilePath);
setImageProfile();
}
private void resultOnCropOkOfGallary(Intent data) {
Bundle extras2 = data.getExtras();
this.bitmap = extras2.getParcelable("data");
setImageProfile();
}
private void resultOnCroppingCancel() {
Log.v("", "do cropping cancel" + cameraImageFilePath);
setImageProfile();
}
private void setImageProfile() {
Log.v("", "cameraImagePath = > " + cameraImageFilePath);
if (ivPicture != null) {
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
String ivPicture =ConDetTenthFragment.getStringImage(bitmap);
Log.d("byte code -", ivPicture);
/*Intent i = new Intent(context, ImageUpload.class);
String getrec = ivPicture;
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("moin", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
context.startActivity(i);*/
} else {
Log.v("", "bitmap is null");
}
}
}
public String getVar1() {
return ivPicture1;
}
/*public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}*/
}
Below is my Fragment Code:
public class ConDetTenthFragment extends Fragment {
static String FileByte;
String FileName;
String resultlog;
ImageView ivProfile;
Context context = getActivity();
Button btnUpload, send;
CameraHandler cameraHandler;
private ProgressDialog pDialog;
static String abc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
/*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));*/
ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
send = (Button) rootView.findViewById(R.id.btnsend);
cameraHandler = new CameraHandler(context);
cameraHandler.setIvPicture(ivProfile);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraHandler.showView();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new async().execute();
}
});
return rootView;
}
public static ConDetTenthFragment newInstance(String text) {
ConDetTenthFragment f = new ConDetTenthFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
public static String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
abc = encodedImage;
//encodedImage = FileByte.setText().toString();
return encodedImage;
}
// Async task to perform login operation
class async extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Get the bundle
/*Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("moin");*/
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty(parameter, abc);//add the parameters
request.addProperty(parameter2, "moin.jpeg");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
// this is the actual part that will call the webservice
androidHttpTransport.call(soap_action, envelope);
// SoapPrimitive prim = (SoapPrimitive) envelope.getResponse(); // Get the SoapResult from the envelope body.
SoapObject response = (SoapObject) envelope.bodyIn;
// resultlog=prim.toString();
hideDialog();
} catch (Exception e) {
e.printStackTrace();
}
return resultlog;
}
}
/*#Override
public void onClick(View view) {
if (view == btnUpload) {
cameraHandler.showView();
}
if (view == send) {
new async().execute();
}
}*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
cameraHandler.onResult(requestCode, resultCode, data);
Log.v("", "code = > " + requestCode);
}
// this is used to show diologue
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
// this is used to hide diologue
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Below is my Log Cat:
FATAL EXCEPTION: main
Process: code.meter.securemeter.com.securemeter, PID: 10492
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Activity.getPackageManager()' on a null object reference
at code.meter.securemeter.com.securemeter.helper.CameraHandler.getActivities(CameraHandler.java:72)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.fillCameraActivities(CameraHandler.java:83)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.showView(CameraHandler.java:106)
at code.meter.securemeter.com.securemeter.fragment.ConDetTenthFragment$1.onClick(ConDetTenthFragment.java:76)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10540)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6856)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Problem is happening because you are passing a null context to CameraHandler
Change your ConDetTenthFragment as follows:
public class ConDetTenthFragment extends Fragment {
Context context;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getAcitivity();
cameraHandler = new CameraHandler(context);
....
}
}
Also, I think you don't need to Cast a context to Activity.
Just call (in CameraHandler):
PackageManager packageManager = context.getPackageManager();
Issue
Basically, the issue happened because you are creating your context as follows:
public class ConDetTenthFragment extends Fragment {
Context context = getActivity();
...
}
When your Fragment is created, context = getActivity() is created also. However, at this time, your fragment is not attached yet and this way, getActivity() returns null.
I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
I have written a program which has a button which when clicked captures a photo through camera and want to set the captured image on the same activity below the button.
Everything works without giving an error. The image is also getting saved to the respective location. But the image is not getting displayed, which means something is going wrong.
Below is my Code for the above :
public class MainActivity extends ActionBarActivity {
Button b1;
private File imageFile;
ImageView img;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.buttonPicture);
img = (ImageView) findViewById(R.id.imageView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"test.jpeg");
uri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
Bitmap photo = (Bitmap) data.getExtras().get(
MediaStore.EXTRA_OUTPUT);
previewCapturedImage();
img.setImageBitmap(photo);
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath(),
options);
img.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
Once you press Ok button after capturing image, you can take the captured image from the Extras using Intent(data in your case) parameter received through onActivityResult
Simply use this code inside onActivityResult
Bitmap photo = (Bitmap) data.getExtras().get("data");
imgViewLogo.setImageBitmap(photo);
Try with below code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
private String selectedImagePath;
Uri selectedImageUri = data.getData();
String filePath = null;
String filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), R.string.unknownPath, Toast.LENGTH_LONG).show();
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
//getPath method
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
//decodeFile method
public void decodeFile(String filePath) {
private Bitmap bitmap;
try {
File f = new File(filePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstudentstreamOutputStream);
img.setImageBitmap(selfieBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
My app is set to only display in portrait mode. The problem is that I need to use a camera and a gallery intent and you can't specify those apps to be the same orientation so some funky stuff happens in between those orientation changes which makes my image data null.
This code works fine when the phone isn't tilted sideways (in portrait mode) how would I improve it to handle data after an orientation change?
public class PostPhotosActivity extends Activity {
public static final String TAG = "PostPhotosActivity";
String title, price, description, maincat, subcat, pname, pemail, pphone, pmeet, imageUri;
public static final String TEMP_PHOTO_FILE_NAME = "temp_photo.jpg";
public static final int REQUEST_CODE_GALLERY = 0x1;
public static final int REQUEST_CODE_TAKE_PICTURE = 0x2;
public static final int REQUEST_CODE_CROP_IMAGE = 0x3;
private ImageView mImageView;
private File mFileTemp;
ParseFile file;
double latitude, longitude;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //To change body of overridden methods use File | Settings | File Templates.
setContentView(R.layout.activity_post_photos);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
title = extras.getString("TITLE"); // get the value based on the key
price = extras.getString("PRICE"); // get the value based on the key
description = extras.getString("DESCRIPTION"); // get the value based on the key
maincat = extras.getString("MAINCAT"); // get the value based on the key
subcat = extras.getString("SUBCAT"); // get the value based on the key
pname = extras.getString("PNAME"); // get the value based on the key
pemail = extras.getString("PEMAIL"); // get the value based on the key
pphone = extras.getString("PPHONE"); // get the value based on the key
pmeet = extras.getString("PMEET"); // get the value based on the key
}
button = (Button) findViewById(R.id.post_data);
button.setVisibility(View.INVISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(PostPhotosActivity.this);
/**
* Set GPS Location fetched address
*/
if (mGpsLocationTracker.canGetLocation())
{
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
Log.i(TAG, String.format("latitude: %s", latitude));
Log.i(TAG, String.format("longitude: %s", longitude));
}
else
{
mGpsLocationTracker.showSettingsAlert();
}
ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
ParseObject setPost = new ParseObject("testData");
// Create an author relationship with the current user
setPost.put("author", ParseUser.getCurrentUser());
// Get location
setPost.put("location", point);
setPost.put("Title", title);
setPost.put("Price", price);
setPost.put("Description", description);
setPost.put("MainCat", maincat);
setPost.put("SubCat", subcat);
setPost.put("PName", pname);
setPost.put("PEmail", pemail);
setPost.put("PPhone", pphone);
setPost.put("PMeet", pmeet);
setPost.put("Photo", file);
setPost.saveInBackground();
Intent intent = new Intent(PostPhotosActivity.this, Flow.class);
startActivity(intent);
}
});
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
takePicture();
} else { // pick from file
openGallery();
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.iv_photo);
mImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE_NAME);
}
else {
mFileTemp = new File(getFilesDir(), TEMP_PHOTO_FILE_NAME);
}
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
/*
* The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "cannot take picture", e);
}
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
private void startCropImage() {
Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
intent.putExtra(CropImage.SCALE, true);
intent.putExtra(CropImage.ASPECT_X, 1);
intent.putExtra(CropImage.ASPECT_Y, 1);
startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
startCropImage();
} catch (Exception e) {
Log.e(TAG, "Error while creating temp file", e);
}
break;
case REQUEST_CODE_TAKE_PICTURE:
startCropImage();
break;
case REQUEST_CODE_CROP_IMAGE:
String path = data.getStringExtra(CropImage.IMAGE_PATH);
if (path == null) {
return;
}
//byte[] idata = path.getBytes();
Bitmap picture = BitmapFactory.decodeFile(path);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// get byte array here
byte[] idata= stream.toByteArray();
file = new ParseFile("photo.jpg", idata);
file.saveInBackground();
bitmap = BitmapFactory.decodeFile(mFileTemp.getPath());
mImageView.setImageBitmap(bitmap);
button.setVisibility(View.VISIBLE);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
]
You could use fragments to retain the information that is being lost by the orientation change.
http://www.vogella.com/articles/AndroidFragments/article.html#headlessfragments2