You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
MpPreview/app/src/main/java/com/xypower/mppreview/PhotoUtil.java

84 lines
2.6 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.xypower.mppreview;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.FileProvider;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PhotoUtil {
/**
* 保存 photoUri
*/
private static Uri photoUri;
/**
* 打开相机
*/
public static void openCamera(Context context, ActivityResultLauncher<Intent> photoResultLauncher) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//确保有相机来处理Intent
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
File photoFile = saveFileName(context);
if (photoFile != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//适配Android 7.0文件权限通过FileProvider创建一个content类型的Uri
photoUri = FileProvider.getUriForFile(context.getApplicationContext(), "com.stg.rouge.activity.fileprovider", photoFile);
} else {
photoUri = getDestinationUri(context);
}
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
photoResultLauncher.launch(takePictureIntent);
}
}
}
/**
* 获取 Uri
*
* @return
*/
private static Uri getDestinationUri(Context context) {
String fileName = String.format("winetalk_%s.jpg", System.currentTimeMillis());
File cropFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
return Uri.fromFile(cropFile);
}
//当前路径,拍照回调后需要使用
private String currentPath = null;
/**
* 保存照片路径
*
* @return
*/
private static File saveFileName(Context context) {
File newFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
String name = format.format(date) + ".jpg";
File ji = null;
try {
ji = new File(newFolder + "/" + name);
ji.createNewFile();
// currentPath = ji.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return ji;
}
}