Take a photo with a camera app and save the full-size photo
Android 2019. 10. 18. 22:57 |반응형
Explains how to take a photo and save the full-size photo in an easy way.
기기의 카메라 앱을 실행 시키고 사진을 찍어 앱 디렉토리에 저장하고 화면에 표시 한다.
<AndroidManifest.xml>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!-- The write permission implicitly allows reading, so if you need to write to the external storage then you need to request only one permission: --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-feature android:name="android.hardware.camera" android:required="true"/> <application ... <provider android:authorities="com.example.myapplication.fileprovider" android:name="androidx.core.content.FileProvider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"> </meta-data> </provider> ... </application> |
<res/xml/file_paths.xml>
1 2 3 4 5 6 | <?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="my_images" path="Android/data/com.example.myapplication/files/Pictures"/> </paths> |
<MainActivity.java>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | public class MainActivity extends AppCompatActivity { static final int PERMISSION_REQUEST_CONTACTS = 1001; static final int REQUEST_TAKE_PHOTO = 2001; ImageView imageView; String currentPhotoPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] permissionRequests = { Manifest.permission.WRITE_EXTERNAL_STORAGE }; checkPermissions(permissionRequests); imageView = findViewById(R.id.imageView); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { File photoFile = null; try { photoFile = createImageFile(); } catch (IOException e) { e.printStackTrace(); } if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), "com.example.myapplication.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(intent, REQUEST_TAKE_PHOTO); } } } }); } public void checkPermissions(String[] permissionRequests) { final ArrayList<String> permissionRequestList = new ArrayList<String>(); for (final String request : permissionRequests) { if (ContextCompat.checkSelfPermission(this, request) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, request)) { // Redundant in this case permissionRequestList.add(request); } else { permissionRequestList.add(request); } } } if (!permissionRequestList.isEmpty()) { final String[] results = new String[permissionRequestList.size()]; permissionRequestList.toArray(results); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("info"); String msg = "This app won't work properly unless you grant below permissions."; for (String str : results) msg += ("\n- "+ str); builder.setMessage(msg); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, results, PERMISSION_REQUEST_CONTACTS); } }); AlertDialog dialog = builder.create(); dialog.show(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CONTACTS: { for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, permissions[i] + " permission granted.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, permissions[i] + " permission denied.", Toast.LENGTH_SHORT).show(); } } } } } private File createImageFile() throws IOException { String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date()); String imageFileName = "IMAGE_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); // If you saved your photo to the directory provided by getExternalFilesDir(), // the media scanner cannot access the files because they are private to your app. File image = File.createTempFile(imageFileName, ".jpg", storageDir); currentPhotoPath = image.getAbsolutePath(); return image; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { Bitmap originalBitmap = BitmapFactory.decodeFile(currentPhotoPath); int scaleFactor = Math.max(originalBitmap.getWidth()/imageView.getWidth(), originalBitmap.getHeight()/imageView.getHeight()); if (scaleFactor < 1) scaleFactor = 1; Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, originalBitmap.getWidth()/scaleFactor, originalBitmap.getHeight()/scaleFactor, true); Matrix m = new Matrix(); m.postRotate(90); Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), m, true); imageView.setImageBitmap(rotatedBitmap); } } } |
Run the app and click CAMERA button.
Take a picture.
The displayed picture is rotated 90 degrees in AVD but is upright in the actual device.
Actual device.
※ Reference:
반응형
'Android' 카테고리의 다른 글
Stream a video file with VideoView 비디오 파일 스트리밍 하기 (0) | 2019.10.22 |
---|---|
Stream an audio file with MediaPlayer 오디오 파일 스트리밍 하기 (0) | 2019.10.21 |
Take a photo with a camera app and get the thumbnail (0) | 2019.10.18 |
Get contact data 연락처 정보 가져오기 (0) | 2019.10.16 |
Get multiple sensor data 여러가지 센서 데이터 받아 오기 (0) | 2019.10.15 |