在Android中,可以使用MediaProjection API和Bitmap类来实现截取屏幕图片并保存到指定文件。通过MediaProjectionManager获取虚拟显示的截屏权限,然后使用Bitmap类的createBitmap方法创建截图,最后将Bitmap保存为文件。
Android实现保存截取屏幕图片到指定文件
在Android应用开发中,截取屏幕并保存为图片是一个常见的需求,本文将详细介绍如何在Android中实现这一功能,包括代码示例和必要的解释。
准备工作
添加权限
需要在AndroidManifest.xml
文件中添加读写存储的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
获取屏幕截图
方法一:使用MediaProjection API
从Android 5.0(API 21)开始,推荐使用MediaProjection
API来获取屏幕截图,这种方法需要用户授予权限,并且适用于截取整个屏幕的内容。
请求截图权限
需要请求截图权限:
import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_CODE = 1; private Button btnTakeScreenshot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnTakeScreenshot = findViewById(R.id.btnTakeScreenshot); btnTakeScreenshot.setOnClickListener(v -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), PERMISSION_CODE); } }); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onActivityResult(int requestCode, resultCode, intent, Bundle data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PERMISSION_CODE) { if (resultCode == RESULT_OK) { takeScreenshot(); } else { // 处理权限被拒绝的情况 } } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void takeScreenshot() { // 实现截图逻辑 } }
实现截图逻辑
实现截图逻辑:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void takeScreenshot() { MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), PERMISSION_CODE); }
保存截图到文件
创建文件
在onActivityResult
中,我们可以创建一个文件来保存截图:
@Override protected void onActivityResult(int requestCode, resultCode, intent, Bundle data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PERMISSION_CODE && resultCode == RESULT_OK) { MediaProjection mediaProjection = (MediaProjection) data.getExtras().get(MediaProjectionManager.EXTRA_RESULT_CODE); if (mediaProjection != null) { saveScreenshotToFile(mediaProjection); } } }
保存文件
private void saveScreenshotToFile(MediaProjection mediaProjection) { ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, format, 2); imageReader.setOnImageAvailableListener(reader -> { Image image = null; try { image = reader.acquireLatestImage(); if (image != null) { Image.Plane[] planes = image.getPlanes(); ByteBuffer buffer = planes[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(bytes)); saveBitmapToFile(bitmap); image.close(); } } finally { if (image != null) { image.close(); } } }, null); mediaProjection.registerCallback(imageReader, callback); }
调用系统截图服务
private void saveBitmapToFile(Bitmap bitmap) { String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/screenshot.png"; File file = new File(path); try { FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
完整代码示例
以下是完整的代码示例,包括布局文件:
// MainActivity.java package com.example.screenshotdemo; import android.Manifest; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.media.ImageReader; import android.media.projection.MediaProjection; import android.media.projection.MediaProjectionManager; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.View; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileOutputStream; import java.nio.ByteBuffer; import android.widget.Button; import android.content.Intent; import android.net.Uri; import androidx.activity.result.contract.ActivityResultContracts; import androidx.core.content.FileProvider; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.activity.result.ActivityResultLauncher; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import java.io.IOException; import androidx.core.content.FileProvider; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
以上就是关于“Android实现保存截取屏幕图片到指定文件”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!