Camera Activity not returns path of image - android

I have task to capture image from camera and send that image to crop Intent. following is the code i have written
for camera capture
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
In on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData(); // picUri is global string variable
performCrop();
}
}
}
public void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 3);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Your device doesn't support the crop action";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
I am getting different behaviours on different devices
In some devices i am getting error "couldn't find item".
In some devices after capturing image activity stuck and doesn't go ahead
I have also tried this
Please tell me the Right way to do this

You can by calling the intent like below:
int REQUEST_IMAGE_CAPTURE = 1;
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));
((Activity) context).startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
And in your activity inside OnActivityResult you get the path like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
ESLogging.debug("Bytes size = " + attachmentBytes.length);
ESLogging.debug("FilePath = " + path);
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) {
ESLogging.error("FileNotFoundException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (IOException e) {
ESLogging.error("IOException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
}
}
}

//Declare this in class
private static int RESULT_LOAD_IMAGE = 1;
String picturePath="";
// write in button click event
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
//copy this code in after onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img); //place imageview in your xml file
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
write the following permission in manifest file
1.read external storage
2.write external storage

try this tutorial http://www.androidhive.info/2013/09/android-working-with-camera-api/ this will help you

Related

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();
}
}

onActivityResult() does not call

The onActivityResult() did not called when I select image from camera or gallery and my activity crashed, my code is below:
private void selectImage() {
final CharSequence[] options = { "cam", "gallery","cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(FragmentActivity4.this);
builder.setTitle("add");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(FragmentActivity4.this);
if (options[item].equals("cam"))
{
if(result){
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("gallery"))
{
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
startActivityForResult(chooserIntent, 2);
}
else if (options[item].equals("cancel")) {
ivImage.setImageDrawable(ContextCompat.getDrawable(FragmentActivity4.this, R.drawable.plusrred));
dialog.dismiss();
}
}
});
builder.show();
}
and in my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode ==Activity.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);
ivImage.setImageBitmap(bitmap);
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.03), (int)(bitmap.getHeight()*0.03), true);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.PNG, 0, baos1);
byte[] imgBytes = baos1.toByteArray();
base64String1 = Base64.encodeToString(imgBytes, Base64.DEFAULT);
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + 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.PNG, 0, 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 = FragmentActivity4.this.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+"");
ivImage.setImageBitmap(thumbnail);
Bitmap thumbnail1 = Bitmap.createScaledBitmap(thumbnail,(int)(thumbnail.getWidth()*0.03), (int)(thumbnail.getHeight()*0.03), true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail1.compress(Bitmap.CompressFormat.PNG,0, baos);
byte[] imgBytes = baos.toByteArray();
base64String1 = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
}
}
My activity extends AppCompatActivity.
Could you please tell me where is the problem?
Here you have
startActivityForResult(chooserIntent, 2);
and in your onActivityResult method you don't include 2 in your if statement. I think the problem is in that.
Your RequestCode is 2.
Change this:
if (requestCode == 1) {
With this:
if (requestCode == 2) {

Android IMAGE_CAPTURE always returns Activity.RESULT_CANCELED

I want to take a photo in my app. On the emulator everything works fine.
But on the tablet, the Intent immediately returns Activity.RESULT_CANCELED in onActivityResult. The picture is saved on the SD Card.
Here is the code for taking picture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String tmpFile = CommonFunctions.generateRandomFileName() + ".jpg";
String fileName = CommonFunctions.getNoticeSavePath() + tmpFile;
System.out.println("Filename " + fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(fileName)));
notice.setBild(tmpFile);
startActivityForResult(intent, RESULT_PICTURE);
Code for onActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_PICTURE:
System.out.println("ResultCode" + resultCode);
if (resultCode == Activity.RESULT_OK) {
}
else if (resultCode == Activity.RESULT_CANCELED){
notice.setBild("");
Toast.makeText(getBaseContext(), "Bild wurde nicht hinzugefĆ¼gt", Toast.LENGTH_LONG).show();
}
break;
}
}
Permissions are set:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
The result is always RESULT_CANCELED, but the photo is stored correctly on the sd card.
What could the problem be?
Do something like this
private static final int REQUEST_CAMERA = 1, SELECT_FILE = 2; //global
onresult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = null;
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 300, 200, true);
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Phoenix" + File.separator + "default";
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("endum_image_", f.toString()).commit();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE)
{
Uri selectedImageUri = data.getData();
//getRealPathFromURI(selectedImageUri);
String tempPath = getPath(selectedImageUri, Signup2Activity.this);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("endum_image_", tempPath).commit();
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath,btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 300, 200, true);
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
}
}
imSex.setImageBitmap(bm);
flag= true;
}

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