카메라 앱 작동 환경 설정 하는 방법
복잡한 로직은 없지만,
보안상의 이유로 설정하는 부분이 많이 복잡하다
보안 작업!!
fileprovider.xml 파일 만들어서 내용 작성한다.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path
name="root"
path="." />
<cache-path
name="cache"
path="." /> <!--Context.getCacheDir() 내부 저장소-->
<files-path
name="files"
path="." /> <!--Context.getFilesDir() 내부 저장소-->
<external-path
name="external"
path="."/> <!-- Environment.getExternalStorageDirectory() 외부 저장소-->
<external-cache-path
name="external-cache"
path="."/> <!-- Context.getExternalCacheDir() 외부 저장소-->
<external-files-path
name="images"
path="Pictures" /> <!-- Context.getExternalFilesDir() 외부 저장소-->
</paths>
AndroidManifest 권한 설정
1.
<uses-feature android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.
<provider
android:authorities="com.닉네임.앱이름.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/fileprovider"/>
</provider>
- 사진 속 권한 작성 위치 확인
라이브러리 설정
- bulid.gradle.kts (Module)에 입력하기
dependencies {
implementation("commons-io:commons-io:2.4")
}
액티비티 설정
- 화면 버튼 눌렀을 때, 카메라를 킬 것인지, 앨범을 열 것인지 선택하는 다이얼로그 사용된다.
- 권한을 확인하는 부분 포함되어 있다.
- 사진의 용량 크기를 정해줄 수 있다.
public class MainActivity extends AppCompatActivity {
Button button;
ImageView imageView;
// 보낼 파일은 멤버변수로 만들어준다.
File photoFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
imageView = findViewById(R.id.imageView);
// 버튼 누르면, 카메라로 찍을것인지, 앨범에서 고를것인지에 대한
// 알러트 다이얼로그 띄운다.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
}
private void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.alert_title);
builder.setItems(R.array.alert_photo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
// 첫번째 항목 눌렀을때
// 카메라로 사진찍기
camera();
}else if(i == 1){
// 두번째 항목 눌렀을때
album();
}
}
});
builder.show();
}
private void camera(){
// 권한 체크
// CAMERE 임포트 안될때, 직접 임포트 하기
// import android.Manifest;
int permissionCheck = ContextCompat.checkSelfPermission(
MainActivity.this, Manifest.permission.CAMERA);
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.CAMERA} ,
1000);
Toast.makeText(MainActivity.this, "카메라 권한 필요합니다.",
Toast.LENGTH_SHORT).show();
return;
} else {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(i.resolveActivity(MainActivity.this.getPackageManager()) != null ){
// 사진의 파일명을 만들기
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
photoFile = getPhotoFile(fileName);
Uri fileProvider = FileProvider.getUriForFile(MainActivity.this,
"Manifest <provider>에 작성한 나의 경로(authorities)", photoFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
startActivityForResult(i, 100);
} else{
Toast.makeText(MainActivity.this, "이폰에는 카메라 앱이 없습니다.",
Toast.LENGTH_SHORT).show();
}
}
}
private void album(){
// 허용했는지 확인
if(checkPermission()){
displayFileChoose();
}else{
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_DENIED){
return false;
}else{
return true;
}
}
private void requestPermission() {
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Log.i("DEBUGGING5", "true");
Toast.makeText(MainActivity.this, "권한 수락이 필요합니다.",
Toast.LENGTH_SHORT).show();
}else{
Log.i("DEBUGGING6", "false");
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 500);
}
}
private void displayFileChoose() {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "SELECT IMAGE"), 300);
}
private File getPhotoFile(String fileName) {
File storageDirectory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try{
return File.createTempFile(fileName, ".jpg", storageDirectory);
}catch (IOException e){
e.printStackTrace();
return null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
break;
}
case 500: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 100 && resultCode == RESULT_OK){
Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
ExifInterface exif = null;
try {
exif = new ExifInterface(photoFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
photo = rotateBitmap(photo, orientation);
// 압축시킨다. 해상도 낮춰서
// 사진 용량이 너무 크면 imageView로 못가져온다 그러면 해상도를 낮추면 된다.
OutputStream os;
try {
os = new FileOutputStream(photoFile);
photo.compress(Bitmap.CompressFormat.JPEG, 25, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
//imageView는 변수 이름
imageView.setImageBitmap(photo);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// 네트워크로 데이터 보낸다.
}else if(requestCode == 300 && resultCode == RESULT_OK && data != null &&
data.getData() != null){
Uri albumUri = data.getData( );
String fileName = getFileName( albumUri );
try {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver( ).openFileDescriptor( albumUri, "r" );
if ( parcelFileDescriptor == null ) return;
FileInputStream inputStream = new FileInputStream( parcelFileDescriptor.getFileDescriptor( ) );
photoFile = new File( this.getCacheDir( ), fileName );
FileOutputStream outputStream = new FileOutputStream( photoFile );
IOUtils.copy( inputStream, outputStream );
// //임시파일 생성
// File file = createImgCacheFile( );
// String cacheFilePath = file.getAbsolutePath( );
// 압축시킨다. 해상도 낮춰서
// 사진 용량이 너무 크면 imageView로 못가져온다 그러면 해상도를 낮추면 된다.
Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
OutputStream os;
try {
os = new FileOutputStream(photoFile);
photo.compress(Bitmap.CompressFormat.JPEG, 25, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
imageView.setImageBitmap(photo);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
// imageView.setImageBitmap( getBitmapAlbum( imageView, albumUri ) );
} catch ( Exception e ) {
e.printStackTrace( );
}
// 네트워크로 보낸다.
}
super.onActivityResult(requestCode, resultCode, data);
}
//앨범에서 선택한 사진이름 가져오기
public String getFileName( Uri uri ) {
Cursor cursor = getContentResolver( ).query( uri, null, null, null, null );
try {
if ( cursor == null ) return null;
cursor.moveToFirst( );
@SuppressLint("Range") String fileName = cursor.getString( cursor.getColumnIndex( OpenableColumns.DISPLAY_NAME ) );
cursor.close( );
return fileName;
} catch ( Exception e ) {
e.printStackTrace( );
cursor.close( );
return null;
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
}
다이얼로그를 띄우는데 필요한 문자열 res/values/string.xml에 작성하기
<resources>
<string name="app_name">CameraApp</string>
<string name="alert_title">선택하세요</string>
<string-array name="alert_photo">
<item>카메라로 사진찍기</item>
<item>앨범에서 가져오기</item>
</string-array>
</resources>
'Android Studio' 카테고리의 다른 글
[Android Studio] 화면 업데이트 하는 방법 _ ArrayList, like (0) | 2024.06.17 |
---|---|
[Android Studio] 네트워크 라이브러리 _ Retrofit2 사용하기 (0) | 2024.06.14 |
[Android Studio] 시간 데이터를 자바 UTC에서 로컬 타임으로 변환 _SimpleDateFormat (2) | 2024.06.14 |
[Android Studio] 액션바 만들고, 해당 엑티비티에서 액션바 보이게 만드는 함수 _onCreateOptionsMenu(Menu menu) (2) | 2024.06.14 |
[Android Studio] 새로운 미니 창 뜨게하는 showAlertDialog() 함수 만들기 (0) | 2024.06.14 |