Android(Java)

안드로이드 버전 별 이미지 저장

E.I.T.U 2022. 3. 16. 11:05
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
    ContentValues contentValues = new ContentValues();
    String path = "fileName";
    contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, path);
    contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM+"/" + folderName + "/");
    ContentResolver contentResolver = activity.getContentResolver();
    Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    try {
        OutputStream outputStream = contentResolver.openOutputStream(uri);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        Log.d("SaveImage", "Success");
    } catch (Exception e){
        e.printStackTrace();
        Log.d("SaveImage", "Failed");
    }

} else if (CheckPermissions()){
    String folder = Environment.getExternalStorageDirectory() + "/DCIM/" + folderName + "/";
    String path = "fileName.jpg";

    try {
        File file_path = new File(folder);

        if (file_path.mkdir()) {
            Log.d("MakeDir", "Success");
        }

        FileOutputStream out = new FileOutputStream(folder + path);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.close();
		Log.d("SaveImage", "Success");

    } catch (FileNotFoundException exception) {
        Log.e("FileNotFoundException", exception.getMessage());

    } catch (IOException exception) {
        Log.e("IOException", exception.getMessage());

    }
}