Take photo w/ camera intent and display in imageView or textView? - android

I have a question about how to take an image using the camera intent (or camera API) and then bring the image into an imageView for me to display in my application. This is what I have so far.
I setup a button
Button btnPicture = (Button) findViewById(R.id.btn_picture);
btnPicture.setOnClickListener(this);
I setup a Camera method
private void Camera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_CODE);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
And this is where I am lost. I am trying to process the image that I took.
private void processImage(Intent intent) {
setContentView(R.layout.imagelayout);
ImageView imageView = (ImageView)findViewById(R.id.image_view);
cameraBitmap = (Bitmap)intent.getExtras().get("data");
imageView.setImageBitmap(cameraBitmap);
}
My intent is to display the image that you took inside image_view. I am not receiving an error, nothing happens. When I take the picture, I am asked to either take another picture or after I use the device back button the application force closes. It seems that I am taken out of my application completely, and returning is a big issue. Any suggestions? What am I missing?
O yea, and here is my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(TAKE_PICTURE_CODE == requestCode) {
Bundle extras = data.getExtras();
if (extras.containsKey("data")) {
Bitmap bmp = (Bitmap) extras.get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] image = baos.toByteArray();
if (image != null) {
Log.d(TAG, "image != null");
}
} else {
Toast.makeText(getBaseContext(), "Fail to capture image", Toast.LENGTH_LONG).show();
}
}
}
I am trying to put the image in getExtras, and then store it to a ByteArray. Was another thing I was trying to do. Not sure how it all comes together.

The method which i found to be easy and helpful is this:
MainActivity
private static String root = null;
private static String imageFolderPath = null;
private String imageName = null;
private static Uri fileUri = null;
private static final int CAMERA_IMAGE_REQUEST=1;
public void captureImage(View view) {
ImageView imageView = (ImageView) findViewById(R.id.capturedImageview);
// fetching the root directory
root = Environment.getExternalStorageDirectory().toString()
+ "/Your_Folder";
// Creating folders for Image
imageFolderPath = root + "/saved_images";
File imagesFolder = new File(imageFolderPath);
imagesFolder.mkdirs();
// Generating file name
imageName = "test.png";
// Creating image here
File image = new File(imageFolderPath, imageName);
fileUri = Uri.fromFile(image);
imageView.setTag(imageFolderPath + File.separator + imageName);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent,
CAMERA_IMAGE_REQUEST);
}
and then in your activity onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CAMERA_IMAGE_REQUEST:
Bitmap bitmap = null;
try {
GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
bitmap = getImageThumbnail.getThumbnail(fileUri, this);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting image image icon on the imageview
ImageView imageView = (ImageView) this
.findViewById(R.id.capturedImageview);
imageView.setImageBitmap(bitmap);
break;
default:
Toast.makeText(this, "Something went wrong...",
Toast.LENGTH_SHORT).show();
break;
}
}
}
GetImageThumbnail.java
public class GetImageThumbnail {
private static int getPowerOfTwoForSampleRatio(double ratio) {
int k = Integer.highestOneBit((int) Math.floor(ratio));
if (k == 0)
return 1;
else
return k;
}
public Bitmap getThumbnail(Uri uri, Context context)
throws FileNotFoundException, IOException {
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;// optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1)
|| (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
: onlyBoundsOptions.outWidth;
double ratio = (originalSize > 400) ? (originalSize / 350) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither = true;// optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
}
and then on the ImageView onclick method will be like this:
public void showFullImage(View view) {
String path = (String) view.getTag();
if (path != null) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.parse("file://" + path);
intent.setDataAndType(imgUri, "image/*");
startActivity(intent);
}
}

To take photo correctly you should store it in temp file, because data in result intent can be null:
final Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
final String pickTitle = activity.getString(R.string.choose_image);
final Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
if (AvailabilityUtils.isExternalStorageReady()) {
final Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final Uri fileUri = getCameraTempFileUri(activity, true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
new Intent[] { takePhotoIntent });
}
activity.startActivityForResult(chooserIntent, REQUEST_CODE);
And then get photo from Uri:
if (requestCode == ProfileDataView.REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
final Uri dataUri = data == null ? getCameraTempFileUri(context,
false) : data.getData();
final ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(imageUri, "r");
final FileDescriptor fd = pfd.getFileDescriptor();
final Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);
}

Related

Cant load picture

I have a problem when I'm trying to load a picture that saved on the phone.
I have a "Helper class"
public class FileHelper {
public static String saveBitmapToFile(Bitmap bitmap, Context context, String fileName) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// write the compressed bitmap to the outputStream(bytes)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
Toast.makeText(context, "בעיה ,", Toast.LENGTH_SHORT).show();
}
try {
fo.write(bytes.toByteArray());
fo.close();// close file output
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
Here's where I'm trying to upload the photo:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
iv = (ImageView) findViewById(R.id.ivPic);
btnTakePic = (Button) findViewById(R.id.btnpic);
btnPickPicture = (Button) findViewById(R.id.btnpicpic);
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
} catch (FileNotFoundException e) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);
}
iv.setImageBitmap(bitmap);
btnTakePic.setOnClickListener(this);
btnPickPicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = null;
if (v == btnTakePic) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
} else if (v == btnPickPicture) {
Intent pickPickIntent = new Intent(Intent.ACTION_PICK);
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String picDirPath = picDir.getPath();
Uri uData = Uri.parse(picDirPath);
pickPickIntent.setDataAndType(uData, "image/*");
startActivityForResult(pickPickIntent, PICK_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
{
bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
FileHelper.saveBitmapToFile(bitmap,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
} else if (requestCode == PICK_PICTURE) {
if (resultCode == RESULT_OK) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
options = new BitmapFactory.Options();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String ImageDecode = cursor.getString(columnIndex);
cursor.close();
options.inSampleSize = 5;
Bitmap bmp = BitmapFactory.decodeFile(ImageDecode, options);
iv.setImageBitmap(bmp);
FileHelper.saveBitmapToFile(bmp,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
}
}
}
and Here is where I am trying to load the saved pic:
private void updateHeader()
{
ImageView ivHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.ivHeader);
try{
bitmap= BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
ivHeader.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
Toast.makeText(getApplicationContext(),"error occured",Toast.LENGTH_LONG);
}
}
I have to say that the Toast message is not shown and There are no errors. App not crashing but the pic stays with no change.
Make sure you have external read storage permission. Here is how to request permission.
PS: Also make sure you have added that permission to AndroidManifest.xml

Returning Imageuri=null (but data extras) from camera capture

while debugging the below code, i am getting the value of picUri as null and i can see as picUri=null data:"Intent" {act=inline-data (has extras)}" in trace. Why does picUri is not having the corresponding uri and have data extras?
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
}
}
}
Here you pass the camera Intent
private void INTENTCAMERA() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And after that captured your image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
Log.e("ResultcapturedImage-->",mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
I have received the data in Bundle in onactivityresult and stored it into a file and got the uri from that file as shown below.
Bundle extras = data.getExtras();
Bitmap var_Bitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
var_Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
try {
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"macro"+File.separator);
createDir.mkdir();
File file = new File(root + "macro" + File.separator +"macro.jpg");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
picUri= Uri.fromFile(file);
} catch (IOException e) {
// e.printStackTrace();
}

Save image in original form and without compressing

I want to save the image without compressing it and want to save it in it's original form i.e. when image is compressed the image size decreases and image become small. I am using native camera for this purpose. I am working in android studio. I am making an app in which i am using a camera to save image. But the image is compressed and is very small and very lower quality.
Below is my code for saving image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(isStoragePermissionGranted())
{
SaveImage(bitmap);
}
}
}else {
switch (requestCode) {
case 1000:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
getLocation();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
}
private void SaveImage(Bitmap finalBitmap) {
File storageDir = new File (String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
String root = storageDir + Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
if (!myDir .exists())
{
myDir .mkdirs();
}
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir,fname);
try {
file.createNewFile();
MediaScannerConnection.scanFile(getApplicationContext(), new String[] {file.getPath()} , new String[]{"image/*"}, null);
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Update 1
For more understanding i am putting my onClick method
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check permission for camera
if(ActivityCompat.checkSelfPermission(MainActivity.this, CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
// Check Permissions Now
// Callback onRequestPermissionsResult interceptado na Activity MainActivity
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{CAMERA},
MainActivity.REQUEST_CAMERA);
}
else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
}
}
});
I searched the solution and found that i can use AndroidBitmapUtil
class so i copy and pasted this class into my project i.e. i created a new class. But i don't know how to use it. Although it is described that i can save image by doing new AndroidBmpUtil().save(bmImage, file);. But again i can't match with my code :(
Any help would be highly appreciated
new AndroidBmpUtil().save(source, sdcardBmpPath);
USER ABOVE LINE OF CODE AND FOLLOW BELOW LINK
https://github.com/ultrakain/AndroidBitmapUtil
Open Camera and save image into some specific directory.
solution number 1
private String pictureImagePath = "";
private void openBackCamera() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 1);}
Handle Image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
File imgFile = new File(pictureImagePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
solution number 2
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
For opening camera use
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "imagename.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
and in your onActivityresult method use
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("imagename.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
yourimageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}

Android - Take/Select picture and put it in the right imageview

Problem: The user may take/select up to 3 photos. I'm having trouble in figuring out how to fill the 3 cases; I'm not sure how I could do to retrieve the corresponding ImageView ID.
I tried the putextra since I'm using
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE), but it seems that it's not possible to use the putextra method (I don't retrieve any extra)
So let me share the code with you and feel free to let me know if you would proceed differently. Thanks a lot!
So here I'm catching the click event and passing the V.getID to the method that will handle the actions related to selecting/taking photos.
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add_item_give_button:
checkAddedItem();
break;
case R.id.add_item_image_1:
selectImage(v.getId());
break;
case R.id.add_item_image_2:
selectImage(v.getId());
break;
case R.id.add_item_image_3:
selectImage(v.getId());
break;
}
}
The selectImage method is called and will handle the alertDialog that will ask if the user wants either to take a picture or to select one. I'm trying to pass the ID in the putExtra method, but nothing is received in the startActivityForResult
public void selectImage(final int imageViewID){
final CharSequence[] options = {getString(R.string.cameral_select_photo_label), getString(R.string.camera_take_photo_label), getString(R.string.common_cancel_label)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.camera_dialog_title_label));
builder.setItems(options, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
#Override
public void onClick(DialogInterface dialog, int which) {
if(options[which].equals(getString(R.string.camera_take_photo_label))){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("ImageViewID", imageViewID);
startActivityForResult(intent, REQUEST_CAMERA);
}
else if(options[which].equals(getString(R.string.cameral_select_photo_label))){
Utils.verifyStoragePermissions(getActivity());
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, getResources().getText(R.string.camera_select_image)),SELECT_FILE);
}
else if(options[which].equals(getString(R.string.common_cancel_label))){
dialog.dismiss();
}
}
});
builder.show();
}
In the startActivityForResult, I don't receive the ImageViewID. So for now, I'm just putting the image in the first ImageView since I'm not able to retrieve the right ID.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == REQUEST_CAMERA){
Log.d("Data content", String.valueOf(data));
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
itemPic1.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE){
Log.d("imageViewOrigin", String.valueOf(data.getIntExtra("imageViewID", 0)));
Uri selectedImageUrl = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getContext(), selectedImageUrl, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
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;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
itemPic1.setImageBitmap(bm);
}
}
}
I would recommend setting tags on the ImageViews. Follow the link, its a similar issue What is the main purpose of setTag() getTag() methods of View?. Let me know if you need more help!
Try this way :
private void openImageIntent(int IMAGE_TYPE) {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "mycapturedImage" + File.separator);
root.mkdirs();
final String fname = getUniqueImageFilename();
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choisir une Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, IMAGE_TYPE);
}
Then retrieve each Image like this :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (resultCode == RESULT_OK) {
if (requestCode == FIRST_IMAGE_INTENT) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
selectedCaptureUri = outputFileUri;
} else {
selectedCaptureUri = data == null ? null : data.getData();
}
//Display image here
} else if (requestCode == SECOND_PICTURE_INTENT) {...}

user Intent send image path to another Activity

sometime i running App on my phone.problem is when i click Ok button after camera was pick photo up,at this moment!App' stop running!in fact,i wanna see Pic on another Activity!Is
take picture:
private void takePhoto() {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
photoUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getActivity(), R.string.take_photo_rem,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), R.string.takePhoto_msg,
Toast.LENGTH_LONG).show();
}
}
album:
private void pickPhoto() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
}
onActivityResult: user intent send image uri
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
Bundle bundle = new Bundle();
bundle.putString(SAVED_IMAGE_DIR_PATH, picPath);
startEx.putExtras(bundle);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
preview image Activity!is getIntent() seted null?
Bundle bundle = getIntent().getExtras();
picPath = bundle.getString(KEY_PHOTO_PATH);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bm = BitmapFactory.decodeFile(picPath, options);
1 - start camera for take image
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment .getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, Const.dbSrNo + "image.jpg");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
2 - write below code in "onActivityResult"
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
File imgFile = new File(Environment.getExternalStorageDirectory(),
"/MyImages/");
/*photo = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg");*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg",options);
imageView2.setImageBitmap(bm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byteImage_photo = baos.toByteArray();
Const.imgbyte=byteImage_photo;
3 - generate one java file Const.java
public class Const {
public static byte[] imgbyte = "";
}
4 - now display that image in your activity using
byte[] mybits=Const.imgbyte;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(mybits, 0, mybits.length, options);
yourImageview.setImageBitmap(bitmap);

Categories

Resources