I have implemented the code for choosing an image from SD or Camera.
But, my image doesn't show up in ImageView and I can't choose an image from SD card.
When I click on an image from SD card it jumps instant back to my Activity.
final String[] items = new String[] {"From Camera","From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
if(which == 0){
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg"));
imageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri);
intent.putExtra("return data",true);
startActivityForResult(intent,PICK_FROM_CAMERA);
}catch(Exception ex){
ex.printStackTrace();
}
dialog.cancel();
}else{
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Complete action using"),PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.imageView);
imagePicker = (ImageButton) findViewById(R.id.image_picker);
imagePicker.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dialog.show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != RESULT_OK)
return;
Bitmap bitmap = null;
String path ="";
if(requestCode == PICK_FROM_FILE) {
imageCaptureUri = data.getData();
path = getRealPathFromURI(imageCaptureUri);
if(path == null)
path = imageCaptureUri.getPath();
if(path != null){
bitmap = BitmapFactory.decodeFile(path);
}
}else{
path = imageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentURI){
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentURI,proj,null,null,null);
if(cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
First you need to use permission WRITE_EXTERNAL_STORAGE in AndroidManifest.xml
In your xml layout :
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#f241c9" />
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Take Photo" />
<Button
android:id="#+id/btnPick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Pick Photo" />
In your activity class :
private static final String TAG = "my_log";
private static final int REQUEST_CAPTURE_FROM_CAMERA = 1;
private static final int REQUEST_PICK_FROM_FILE = 2;
private static final int REQUEST_CROP_INTENT = 3;
ImageView img;
Button btnCapture, btnPick;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnPick = (Button) findViewById(R.id.btnPick);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg");
// put Uri as extra in intent object
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA);
}
});
btnPick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) {
try {
cropImage(Uri.fromFile(file));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_PICK_FROM_FILE) {
try {
cropImage(data.getData());
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_CROP_INTENT) {
// Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap from extras
Bitmap bitmap = extras.getParcelable("data");
img.setImageBitmap(bitmap);
if (saveBitmapToStorage(bitmap)) {
Log.d(TAG, "Bitmap saved to file successful.");
} else {
Log.d(TAG, "Failed to save Bitmap to storage.");
}
}
}
public void cropImage(Uri picUri) {
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, REQUEST_CROP_INTENT);
}
private boolean saveBitmapToStorage(Bitmap finalBitmap) {
boolean result = false;
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg");
Log.d(TAG, "file path = " + file.getAbsolutePath());
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// send Broadcast to notify this photo and see it in Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Related
I have an app with image cropping option. After cropping the actual image, the cropped image is saved in gallery. My question is how to retrieve the file name and path of the cropped image saved in gallery.
my code is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I have tried a lot but not retrieving the file name and path. Is there any solution.
You are using startActivityForResult(), but do you override onActivityResult()? In your case you need to do the following:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
{
Uri pictureUri = data.getData();
}
}
This code gets the Uri of the picture. Then you can use this Uri to get the path, using a method like below:
private 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();
}
}
}
EDIT
After you crop the Bitmap and ready to go, you can save it with something like this:
private Uri saveOutput(Bitmap croppedImage)
{
Uri saveUri = null;
// Saves the image in cache, you may want to modify this to save it to Gallery
File file = new File(getCacheDir(), "cropped");
OutputStream outputStream = null;
try
{
file.getParentFile().mkdirs();
saveUri = Uri.fromFile(file);
outputStream = getContentResolver().openOutputStream(saveUri);
if (outputStream != null)
{
croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} catch (IOException e)
{
// log the error
}
return saveUri;
}
After getting the Uri, you can get path to cropped image with the same method above.
I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.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(), "Image.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();
}
#SuppressLint("Assert")
#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());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} 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);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
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();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});
I am working on a project where I have two choices, either I click a photo and the same image is attached to the mail and can be sent. The second is I select the image from the gallery and the image selected is sent as an attachment in the mail.I am able to do the later part but have problem in attaching image after clicking it using camera.
public class MainActivity extends Activity implements OnClickListener {
Button select;
ImageView photo;
EditText et_subject, et_message;
TextView tv_attach;
String subject, message;
private static final int PICK_IMAGE = 100;
Uri URI = null;
Uri URI1= null;
int columnindex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
select = (Button)findViewById(R.id.button1);
photo = (ImageView)findViewById(R.id.imageView1);
et_subject = (EditText)findViewById(R.id.editText1);
et_message = (EditText)findViewById(R.id.editText2);
tv_attach = (TextView)findViewById(R.id.textView1);
photo.setOnClickListener(this);
select.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageView1:
selectImage();
break;
case R.id.button1:
subject = et_subject.getText().toString();
message = et_message.getText().toString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"example#xyz.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
if (URI != null || URI1 != null)
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
startActivity(emailIntent);
break;
default:
break;
}
}
#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(), "temp.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);
photo.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
URI1 = Uri.parse("file://" + path);
//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);
URI = Uri.parse("file://" + picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
photo.setImageBitmap(thumbnail);
}
}
}
}
I've tried something but seems I'm wrong.
Please help me what can be done? Can anybody make changes in the code that I've used?
I tried it and it worked for me, hope it helps!
mail_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake#fake.edu"});
i.putExtra(Intent.EXTRA_SUBJECT,"On The Job");
//Log.d("URI#!##!#!###!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
i.setType("image/png");
startActivity(Intent.createChooser(i,"Share you on the jobing"));
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
I am trying to let to user crop images after taking them / choosing from gallery. Now, the cropping after selecting from gallery works but not camera. Below are my codes, I am not getting any error message. We followed http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/
//Camera button clicked
public void camera_click(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
//Result of camera capture
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//camera
if (requestCode == CAMERA_PIC_REQUEST) {
mImageCaptureUri = data.getData();
performCrop();
}
if (requestCode == PIC_CROP) {
//get the returned data
try{
Bundle extras = data.getExtras();
//get the cropped bitmap
thumbnail = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView image = (ImageView) findViewById(R.id.test_image);
//display the returned cropped image
image.setImageBitmap(thumbnail);
TextView imgTv = (TextView) findViewById(R.id.imageInfo);
String desc = imgTv.getText().toString();
if (desc.equalsIgnoreCase("")) {
String errorMessage = "Please enter a description before submitting a photo.";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
} else {
}
}
catch(Exception ex)
{
Log.i("err", ex.getMessage());
}
}
//gallery selected
if (requestCode == SELECT_PHOTO) {
if (data != null) {
Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
cursor.moveToFirst(); //if not doing this, 01-22 19:17:04.564: ERROR/AndroidRuntime(26264): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
thumbnail = BitmapFactory.decodeFile(fileSrc); //load preview image
thumbnail = android.graphics.Bitmap.createScaledBitmap(thumbnail, 100, 100, true);
// ImageView image = (ImageView) findViewById(R.id.test_image);
// image.setImageBitmap(thumbnail);
ImageButton cam = (ImageButton) findViewById(R.id.camera);
// cam.setVisibility(View.INVISIBLE);
ImageButton gal = (ImageButton) findViewById(R.id.gallery);
mImageCaptureUri = data.getData();
// gal.setVisibility(View.INVISIBLE);
performCrop();
} else {
//Log.d(LOG_TAG, "idButSelPic Photopicker canceled");
// m_Tv.setText("Image selection canceled!");
}
}
}
}//end onactivity results
//method to luanch crop image
private void performCrop() {
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(mImageCaptureUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
} catch (ActivityNotFoundException anfe) {
//display an error message
Log.i("err", anfe.getLocalizedMessage());
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
Intent myIntent = new Intent();
startActivityForResult(myIntent, PIC_CROP);
}
}
This line is probably giving you this problem:
mImageCaptureUri = data.getData();
Delete this and check it out.
If not, I could give you a working code.
Working sample:
Include also this library: https://github.com/lvillani/android-cropimage
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
if(data != null){
mImageCaptureUri = data.getData();
doCrop();
}
break;
case CROP_FROM_CAMERA:
if(data != null){
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
imagebutton.setImageBitmap(photo);
imagebutton.setScaleType(ScaleType.FIT_XY);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
}
break;
}
}
private void doCrop() {
// TODO Auto-generated method stub
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setClassName("com.android.camera", "com.android.camera.CropImage");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(getActivity(), "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getActivity().getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
CropOption class:
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
CropOptionAdapter:
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
frnds,on clicking on button i open camera for taking picture ,i take picture successfull and now only two option is coming after clicking pic,"save" and "Discard",there is not any option for attaching the camera clicked image so how to attach image and display image in next view?
my code is ...
public void function2(int id){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST||requestCode == SELECT_PICTURE) {
try{
try{
selectedImageUri = data.getData();
//OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
//DEBUG PURPOSE - you can delete this if you want
if(selectedImagePath!=null){
Intent i=new Intent(MainMenu.this,Imageprview.class);
startActivity(i);
System.out.println(selectedImagePath);
}
else
System.out.println("selectedImagePath is null");
if(filemanagerstring!=null)
System.out.println(filemanagerstring);
else System.out.println("filemanagerstring is null");
//NOW WE HAVE OUR WANTED STRING
if(selectedImagePath!=null)
System.out.println("selectedImagePath is the right one for you!");
else
System.out.println("filemanagerstring is the right one for you!");
}catch (NullPointerException e) {
// TODO: handle exception
} }catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
} }
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
Button btnCam=(Button)findViewById(R.id.camBtn);
btnCam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
//startActivity(detailActivity);
saveImage();
} });
}
public void saveImage()
{
try {
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK){
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
IN DETAIL PROFILE ACTIVITY
public class detailProfile extends Activity{
String fname=new File(getFilesDir(),"MyFile.jpeg").getAbsolutePath();
//USING THIS FILE PATH YOU CAN LOAD THE IMAGE IN THIS ACTIVITY
}
YOU HAVE ANOTHER OPTION YOU CAN PASS THE IMAGE TO THROUGH THE INTENT AT THE TIME OF CREATING THE NEW INTENT AND AFTER THAT YOU CAN ACCESS THAT IMAGE THROUGH THE BUNDLE OBJECT IN THE NEW INTENT.
bytes[] imgs = ... // your image
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("img", imgs);
startActivity(intent)
in detailprofile
bytes[] receiver = getIntent().getExtra("imgs");
//using Byte array you can display your image in ur imageview
There is no such option available.you can save file in to sdcard or any external storage
c the code i have done for saving image in external storage.
public void onClick(View v)
{
if(v == imgForPhotograph) {
path = Environment.getExternalStorageDirectory() + "/photo1.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.gc();
if (requestCode == CAPTURE_IMAGE_ACTIVITY) {
if (resultCode == Activity.RESULT_OK) {
try {
// Call function MakeFolder to create folder structure if
// its not created
if(imageBitmap != null) {
imageBitmap = null;
imageBitmap.recycle();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(path, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm
byte[] bmpbyte = baos.toByteArray();
//
Imagebase64= Base64.encodeToString(bmpbyte, Base64.DEFAULT); // set
imgForPhotograph.setImageBitmap(imageBitmap);
isImageTaken = true;
// Name for image
IMAGEPATH = getString(R.string.Image)
+ System.currentTimeMillis();
SaveImageFile(imageBitmap,IMAGEPATH);
} catch (Exception e) {
Toast.makeText(this, "Picture Not taken",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
All The Best....
Hi guys, this code is working. For camera and stored into sd card:
public class CampicsaveActivity extends Activity
{
/** Called when the activity is first created. */
FrameLayout frm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frm=(FrameLayout)findViewById(R.id.preview);
Button btnCam=(Button)findViewById(R.id.buttonClick);
btnCam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
// startActivity(detailActivity);
saveImage(0);
} });
}
public void saveImage(int IMAGE_CAPTURE)
{
try
{
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e)
{;}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),CampicsaveActivity.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
}
}