Guest User

Untitled

a guest
Jan 19th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. public class MyActivity extends Activity {
  2.  
  3. private Button btn;
  4. private ImageView imageView;
  5.  
  6. private static final File photoPath = new File(Environment.getExternalStorageState(), "camera.jpg");
  7.  
  8. private static final int CAMERA = 1;
  9.  
  10. /**
  11. * Called when the activity is first created.
  12. */
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17.  
  18. findViews();
  19. setListeners();
  20. }
  21.  
  22. private void setListeners() {
  23. btn.setOnClickListener(new View.OnClickListener() {
  24. @Override
  25. public void onClick(View v) {
  26. Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  27. intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoPath));
  28. startActivityForResult(intent, CAMERA);
  29. }
  30. });
  31. }
  32.  
  33. private void findViews() {
  34. btn = (Button) findViewById(R.id.btn);
  35. imageView = (ImageView) findViewById(R.id.imageView);
  36. }
  37.  
  38. @Override
  39. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  40. super.onActivityResult(requestCode, resultCode, data);
  41. if (requestCode == CAMERA) {
  42. if (resultCode == RESULT_OK) {
  43. try {
  44. Bitmap bitmap = getCameraBitmap(data);
  45. if (bitmap == null) {
  46. Toast.makeText(MyActivity.this, "Can't get bitmap from camera", Toast.LENGTH_LONG).show();
  47. } else {
  48. imageView.setImageBitmap(bitmap);
  49. }
  50. } catch (IOException e) {
  51. Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
  52. }
  53. }
  54. }
  55. }
  56.  
  57. public Bitmap getCameraBitmap(Intent data) throws IOException {
  58. if (data == null) {
  59. // try solution 1
  60. try {
  61. return MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(photoPath));
  62. } catch (FileNotFoundException e) {
  63. return BitmapFactory.decodeFile(photoPath.getAbsolutePath());
  64. }
  65. } else {
  66. Uri image = data.getData();
  67. if (image != null) {
  68. // try solution 3
  69. InputStream inputStream = getContentResolver().openInputStream(image);
  70. return BitmapFactory.decodeStream(inputStream);
  71. } else {
  72. // try solution 4
  73. return (Bitmap) data.getExtras().get("data");
  74. }
  75. }
  76. }
  77. }
Add Comment
Please, Sign In to add comment