Android/멀티미디어
[ Android ] 임시 파일 생성해서 외부 앱으로 찍은 사진 받기
cat_cat
2020. 9. 16. 20:21
resolveActivity()
takePictureIntent.resolveActivity(getPackageManager())
결과가 null이 아닌 경우, 인텐트를 처리할 수 있는 앱이 최소한 하나는 있다는 뜻이며 startActivity()를 호출해도 안전합니다. 결과가 null이면 해당 인텐트를 사용해서는 안 되고, 가능하면 해당 인텐트를 호출하는 기능을 비활성화해야 합니다.
Code
<provider
android:authorities="${applicationId}.provider"
android:name="androidx.core.content.FileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
<paths>
<external-path
name="images"
path="."/>
</paths>
public class ReportCameraActivity extends AppCompatActivity {
private File filePath;
private ImageView resultView;
private String currentPhotoPath;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_camera);
resultView = findViewById(R.id.resultImageView);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
filePath = dispatchTakePictureIntent();
}
}
private File dispatchTakePictureIntent() {
Uri photoURI;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(Objects.requireNonNull(getApplicationContext()),
BuildConfig.APPLICATION_ID+".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, Constants.CAMERA_REQUEST_CODE);
}
return photoFile;
}
return null;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/**
* 이미지의 크기와 프로그램에서 사용하려는 이미지 크기를 비교해서 비율을 동적으로 결정
**/
if (filePath != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
InputStream in = new FileInputStream(filePath);
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;
} catch ( Exception e ) {
e.printStackTrace();
}
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
final int repWidth = 300;
final int reqHeight = 300;
// width, height 값에 따라 inSaampleSize 값 계산
if (height > reqHeight || width > repWidth) {
final int heightRatio = Math.round((float) height/(float)reqHeight);
final int widthRatio = Math.round((float) height/(float)repWidth);
inSampleSize = (heightRatio < widthRatio)? heightRatio : widthRatio;
}
BitmapFactory.Options imgOptions = new BitmapFactory.Options();
imgOptions.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory
.decodeFile(filePath.getAbsolutePath(), imgOptions);
resultView.setImageBitmap(bitmap);
}
}
}
}