본문 바로가기

안드로이드

android 10 이상 스크린 캡쳐 후 파일저장(screen capture view java)

반응형

public static void takeScreenshot(View v) {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
    try {
        String fileName = "android_scshot_" + now + ".jpg";
        View v1 = v;
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        int quality = 100;

        OutputStream fos;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = v1.getContext().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
            Uri imageUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
            fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
        } else {
            String imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            File image = new File(imagesDir, fileName);
            fos = new FileOutputStream(image);
        }

        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
        fos.flush();
        fos.close();

        CommonUtils.showToast("이미지가 캡쳐 되었습니다.", v.getContext());

    } catch (IOException e) {
        e.printStackTrace();
    }
    
}

반응형

'안드로이드' 카테고리의 다른 글

PDF 파일 불러와서 Sign하기(JAVA)  (0) 2024.01.08
이미지 공유시 Uri 얻기  (0) 2023.12.14
rxjava 파일 다운로드  (0) 2023.11.13
코틀린 apply, run, let  (0) 2023.11.10
자바 특정일에 다음날 이전날  (0) 2023.09.19