button1.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.R)
@Override
public void onClick(View view) {
View view1 = getWindow().getDecorView();
Bitmap bitmap = testViewSnapshot(view1);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
System.out.println("Bitmap weight = "+width+" Bitmap height "+height);
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 100, bitmap.getWidth() , bitmap.getHeight()/2);
saveImageToGallery2(view.getContext(), bitmap1);
Toast.makeText(FirstActivity.this, "button1 Clicked.", Toast.LENGTH_SHORT).show();
}
});
@RequiresApi(api = Build.VERSION_CODES.R)
public static void saveImageToGallery2(Context context, Bitmap image){
Long mImageTime = System.currentTimeMillis();
String imageDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(mImageTime));
String SCREENSHOT_FILE_NAME_TEMPLATE = "IMG%s.png";
String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
final ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM
+ File.separator + "Camera");
values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
values.put(MediaStore.MediaColumns.DATE_EXPIRES, DateUtils.SECOND_IN_MILLIS*5);
System.out.println("xxxx"+(mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
try (OutputStream out = resolver.openOutputStream(uri)) {
if (!image.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
throw new IOException("Failed to compress");
}
}
values.clear();
values.put(MediaStore.MediaColumns.IS_PENDING, 0);
resolver.update(uri, values, null, null);
Toast.makeText(context,"保存图片成功",
Toast.LENGTH_SHORT).show();
}catch (IOException e){
resolver.delete(uri, null);
Toast.makeText(context,"失败",
Toast.LENGTH_SHORT).show();
}
}