안드로이드 자바
[Java][Android] 화면 캡처해서 갤러리에 저장하기
teamnova
2024. 11. 14. 12:00
728x90
안녕하세요.
오늘은 화면캡처를 해서 갤러리에 저장하는 기능을 구현해보겠습니다.
우선 전체 코드입니다.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button captureButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureButton = findViewById(R.id.captureButton);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
captureScreen();
}
});
}
private void captureScreen() {
// 전체 화면의 뷰 가져오기
View rootView = getWindow().getDecorView().getRootView();
// 화면을 Bitmap으로 변환
rootView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
// Bitmap을 파일로 저장
saveBitmapToMediaStore(bitmap);
}
private void saveBitmapToMediaStore(Bitmap bitmap) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, "screenshot_" + System.currentTimeMillis() + ".png");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/ScreenCaptures");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (uri != null) {
try (OutputStream outputStream = getContentResolver().openOutputStream(uri)) {
if (outputStream != null) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
Toast.makeText(this, "갤러리에 저장되었습니다.", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "저장에 실패했습니다.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "저장소에 접근할 수 없습니다.", Toast.LENGTH_SHORT).show();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/captureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="화면 캡처"
android:layout_centerInParent="true"/>
</RelativeLayout>
[화면 캡처] 버튼을 누르면 captureScreen() 메서드가 호출됩니다.
이때, 화면 전체 루트뷰를 가져오게 되고, 이것을 Bitmap 객체로 저장합니다.
이 Bitmap 객체를 saveBitmapToMediaStore(bitmap) 메서드로 전달합니다.
saveBitmapToMediaStore(bitmap) 메서드 에서는, MediaStore API 를 사용하여 갤러리에 저장합니다.
시연 영상입니다.