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));
}
}
}
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 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 was selected the image after it have to set it in the imageview.But it doesn't set it in imageview.
I have posted the relevant code.
EditViewProfileActivity.java
public class EditViewProfileActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CAMERA_PICTURE = 1;
private static final int GALLERY_PICTURE = 2;
File destination = null;
String filePath = null;
Bitmap chosenImage;
String imgSelected = null;
ImageView dateBirthImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_view_profile_activity);
galImageView = (ImageView) findViewById(R.id.gallery_image_edit_view);
galImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePictureAction();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
destination = new File(selectedImagePath);
filePath = selectedImagePath;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
chosenImage = BitmapFactory.decodeFile(selectedImagePath, options);
if (chosenImage != null) {
imgSelected = "fulFilled";
galImageView.setImageBitmap(chosenImage);
Log.e("ChosenImage", "" + chosenImage);
}
} else if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_CANCELED) {
}
}
private void choosePictureAction() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(EditViewProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PICTURE);
} else if (items[which].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_PICTURE);
} else if (items[which].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
I dont know why selected image not showing in imageview.Anyone can help me with this.Thank you.
I Have use this code:
private void openGallery() {
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
try {
bitmaps = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmaps.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byteArray = stream.toByteArray();
encodeded = Base64.encodeToString(byteArray, Base64.DEFAULT);
byte[] decodedString = Base64.decode(encodeded, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
userinfoimage.setImageBitmap(bitmaps);
new UploadImage().execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you only want to set image in imageview. you can directly use the uri. Like this
String stringUri = selectedImageUri.getPath();
galImageView.setImageURI(null);
galImageView.setImageURI(Uri.parse(stringUri));
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;
}
Hi I have created an Activity from that I am calling startActivityForResult at the first time it is working below is the code
Dialog box for choosing image from Camera or Gallery
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(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")) {
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
It's onActivityForResultSetMethod
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("onActivityResult");
System.out.println("requestCode : - " + requestCode);
System.out.println("resultCode : - " + resultCode);
System.out.println("data : - " + data);
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
imagePath = getAbsolutePath(data.getData());
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else if (requestCode == CAPTURE_IMAGE) {
imagePath = getImagePath();
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
Issue if when i first time called, In image view i am not getting image, and also if i tried it again
Activity's onCreate method is also called don't know but why
Try this way,hope this will help you to solve your problem.
private int PICK_IMAGE=1;
private int CAPTURE_IMAGE=2;
private String imgPath;
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(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")) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
} else if (requestCode == CAPTURE_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getImagePath()));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
Note : please not forget this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try This : I have done some modification.It is working on my end
public class MainActivity extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btnSelectPhoto);
viewImage = (ImageView) findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp1.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "AudioBlog" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
try this
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(
ProfileActivity.this);
// builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Take a Photo",
"Choose from Gallery" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
break;
default:
break;
}
}
});
builder.show();
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
onActivityForResultSetMethod
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
System.out.println("path" + selectedImagePath);
imageView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
System.out.println("path" + selectedImagePath);
imageView.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(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;
}
As to called onCreate(), please Log.d("~~~",""+savedInstanceState);, it will likely be non-null meaning that Android advices you to restore the application state from the bundle.