모바일개발(Mobile Dev)/안드로이드개발(Android)
when using imageView in camera
테크한스
2017. 7. 8. 11:55
반응형
written by https://stackoverflow.com/questions/34504717/android-app-crashes-on-onactivityresult-while-using-camera-intent/34626655
Follow below steps in order to take picture from camera and display onto ImageView
1) Start Camera Intent
Uri fileUri;
String photoPath = "";
private void startingCameraIntent()
{
String fileName = System.currentTimeMillis()+".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, YOUR_REQ_CODE);
}
2) Callback onActivityResult Function
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
try
{
photoPath = getPath(fileUri);
System.out.println("Image Path : " + photoPath);
Bitmap b = decodeUri(fileUri);
your_image_view.setImageBitmap(b);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
3) decodeUri Function
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 72;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
{
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage), null, o2);
return bitmap;
}
4) getPath of Image
@SuppressWarnings("deprecation")
private String getPath(Uri selectedImaeUri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(selectedImaeUri, projection, null, null,
null);
if (cursor != null)
{
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(columnIndex);
}
return selectedImaeUri.getPath();
}
Finally In Manifest define permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Note: If you are using marshmallow (Android 6.0) you have to set Permission checks before using camera app. You can read about Android Requesting Permissions at Run Time
반응형