private static final int CHOOSE_PHOTO = 2;
private static final int APPLY_PERMISSION = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitImagePath();
}
public void showPicturePicker(Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("图片来源");
builder.setNegativeButton("取消", null);
builder.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
break;
case 1:
break;
default:
break;
}
}
});
builder.create().show();
}
//Android6.0开始,WRITE_EXTERNAL_STORAGE被认为是危险权限,需要动态申请
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE},
APPLY_PERMISSION);
} else
openAlbum();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case APPLY_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
}
break;
}
}
private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
pictureBusy = false;
//sensorManager.unregisterListener(listener);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
String path = "";
if (Build.VERSION.SDK_INT >= 19) {
//4.4及以上系统使用这个方法处理图片
path = handleImageOnKitKat(data);
} else {
//4.4以下使用这个方法处理图片
path = handleImageBeforeKitKat(data);
}
String dbDir1 = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
dbDir1 += "/XM1.U/image";//图片路径
long timeMillis = Calendar.getInstance().getTimeInMillis();
imageNoNamePath = dbDir1;
imageName = "temp.jpg";
imagePath = imageNoNamePath + "/" + imageName;
copyFile(path, imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
int degree = PhotoRotateUtil.getBitmapDegree(imagePath);
bitmap = rotateBitmapByDegree(bitmap, degree);
ivPicture.setImageBitmap(bitmap);
test.setText("");
}
break;
default:
break;
}
}
private String handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
return imagePath;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private String handleImageOnKitKat(Intent data) {
String imgPath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
//如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];//解析出数字格式的id
String selection = MediaStore.Images.Media._ID + "=" + id;
imgPath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contenturi = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imgPath = getImagePath(contenturi, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content类型的uri,使用普通方法处理
imgPath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是File类型的Uri,直接获取图片路径即可
imgPath = uri.getPath();
}
return imgPath;
}
//通过Uri和selection来获取真实的图片路径
private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
public class PhotoRotateUtil {
/**
* 读取图片的旋转的角度
*
* @param path 图片绝对路径
* @return 图片的旋转角度
/
public static int getBitmapDegree(String path) {
int degree = 0;
try {
// 从指定路径下读取图片,并获取其EXIF信息
ExifInterface exifInterface = new ExifInterface(path);
// 获取图片的旋转信息
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/*
* 将图片按照某个角度进行旋转
*
* @param bm
* 需要旋转的图片
* @param degree
* 旋转角度
* @return 旋转后的图片
*/
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
// 根据旋转角度,生成旋转矩阵
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
// 将原始图片按照旋转矩阵进行旋转,并得到新的图片
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return returnBm;
}
}
//region 拍照事件处理
/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
// int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
// int length;
while ( (byteread = inStream.read(buffer)) != -1) {
// bytesum += byteread; //字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
void InitImagePath()
{
/**
* 创建File对象,用于存储拍照后的图片
* 调用getExternalCacheDir方法可以得到应用关联目录 /sdcard/Android/data//cache
* 为何调用getExternalCacheDir?
* 因为Android从6.0开始。读写SD卡被认为是危险权限。如果将图片放在其他目录,需要动态申请权限
* 而使用关联目录可以跳过这一步
* */
String dbDir1 = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
dbDir1 += "/XM1.U/image";//图片路径
//long timeMillis = Calendar.getInstance().getTimeInMillis();
imageNoNamePath = dbDir1;
imageName = "temp.jpg";
imagePath = imageNoNamePath + "/" + imageName;
File outputImage = new File(imagePath);
try {
if (outputImage.exists())
outputImage.delete();
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
/**
* 从Android7.0开始,直接使用本地的真是路径的URI被认为是不安全的,会抛出FileUriExposeException
* 而FileProvider是一种特殊的ContentProvider,可以给外部选择性的分享Uri,提高安全性*/
imageUri = FileProvider.getUriForFile(MainActivity.this,
"com.app.myapplication",
outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
}