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.
Related
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.
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 code, can anyone help me, where can i put crop image code when asked to select image from gallery or camera. thanks in advance.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
//public static final String UPLOAD_URL = "http://192.168.0.137/image_json /upload.php";
public static final String URL_ADD = "http://192.168.0.104/image_json/addEmp.php";
public static final String URL_GET_ALL = "http://192.168.0.137/image_json/getAllEmp.php";
public static final String URL_GET_EMP = "http://192.168.0.137/image_json/getEmp.php?id=";
public static final String URL_UPDATE_EMP = "http://192.168.0.137/image_json/updateEmp.php";
public static final String URL_DELETE_EMP = "http://192.168.0.137/image_json/deleteEmp.php?id=";
// Keys that will be used to send the request to php scripts
public static final String KEY_EMP_ID = "id";
public static final String KEY_EMP_NAME = "name";
public static final String KEY_EMP_DESG = "desg";
public static final String KEY_EMP_SAL = "salary";
// JSON Tags
public static final String TAG_JSON_ARRAY = "result";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_DESG = "desg";
public static final String TAG_SAL = "salary";
// employee id to pass with intent
public static final String EMP_ID = "emp_id";
public static final String UPLOAD_KEY = "image";
private int PICK_IMAGE_REQUEST = 1;
int REQUEST_CAMERA = 0;
private Button buttonChoose;
private Button buttonUpload;
// private Button buttonView;
private EditText editTextName;
private EditText editTextDesg;
private EditText editTextSal;
private Button buttonAdd;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDesg = (EditText) findViewById(R.id.editTextDesg);
editTextSal = (EditText) findViewById(R.id.editTextSalary);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
// Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
// buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
// buttonView.setOnClickListener(this);
}
private void addEmployee() {
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String sal = editTextSal.getText().toString().trim();
class AddEmployee extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Adding...",
"Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... v)
{
String uploadImage = getStringImage(bitmap);
HashMap<String, String> params = new HashMap<String, String>();
params.put(KEY_EMP_NAME, name);
params.put(KEY_EMP_DESG, desg);
params.put(KEY_EMP_SAL, sal);
params.put(UPLOAD_KEY, uploadImage);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(URL_ADD, params);
Log.i("result",""+res);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(
getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
/*
* Bundle extras = data.getExtras(); Bitmap photo = (Bitmap)
* extras.get("data");
*/
bitmap = getImageFileFromSDCard("abc.jpg");
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "bundal is null",
Toast.LENGTH_LONG).show();
}
}
private Bitmap getImageFileFromSDCard(String filename) {
Bitmap bitmap = null;
File outputFile = Environment.getExternalStorageDirectory();
File file = new File(outputFile, filename);
Log.i("pathstore", "" + file);
try {
FileInputStream fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
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;
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
selectImage();
// showFileChooser();
}
if (v == buttonAdd) {
addEmployee();
}
}
private void viewImage() {
// startActivity(new Intent(this, ImageListView.class));
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
String userChoosenTask = "Take Photo";
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
String userChoosenTask = "Choose from Library";
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "abc.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),
PICK_IMAGE_REQUEST);
}
}
You can do cropping part in onActivityResult method as it is called just after you select photo from gallery or camera.
I hope this answer will help you.
Use your Intent like this.
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
Good Luck!
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 can capture an image, either through camera or gallery. I also have two imageviews to set the captured images to it. But I always get the failed binder transaction when I try to start an intent with the passed two compressed bitmaps:
public class PostFragment extends Fragment implements OnClickListener {
View post_view;
Button button1, button0;
ActionBar actionBar;
private Uri mImageCaptureUri;
private ImageView mImageView, mImageView2;
private AlertDialog dialog;
private String imagepath = null;
Bitmap bitmap, bitmap1, bitmap2, bitmap_image1, bitmap_image2;
String krt, krt1, krt2;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
post_view = inflater.inflate(R.layout.postoffer_fragment_layout,
container, false);
getActivity().getActionBar().setIcon(R.drawable.ic_offer);
button1 = (Button) post_view.findViewById(R.id.button1);
button1.setOnClickListener(this);
button0 = (Button) post_view.findViewById(R.id.button0);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
captureImageInitialization();
mImageView = (ImageView) post_view.findViewById(R.id.imageView1);
mImageView2 = (ImageView) post_view.findViewById(R.id.imageView2);
return post_view;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// setText() sets the string value of the TextView
Intent intent = new Intent(getActivity(), OfferInformation.class);
if (krt1 != "" && krt2 != "") {
intent.putExtra("image", krt1);
intent.putExtra("image2", krt2);
startActivity(intent);
}
}
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
/*tbd
*/
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
mImageView.setTag("2");
/*tbd
*/
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap1);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
byte[] imageBytes1 = baos1.toByteArray();
krt1 = Base64.encodeToString(imageBytes1, Base64.DEFAULT);
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView2.setImageBitmap(bitmap2);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
}
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}