一些新设备不保存位图所以我解释了一点..
确保您已在权限下方添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
xml
并在文件夹名称provider_paths.xml下创建一个 xml 文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
并且在 AndroidManifest 下
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
然后只需调用 saveBitmapFile(passYourBitmapHere)
public static void saveBitmapFile(Bitmap bitmap) throws IOException {
File mediaFile = getOutputMediaFile();
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, getQualityNumber(bitmap), fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
在哪里
File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"easyTouchPro");
if (mediaStorageDir.isDirectory()) {
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(Calendar.getInstance().getTime());
String mCurrentPath = mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg";
File mediaFile = new File(mCurrentPath);
return mediaFile;
} else { /// error handling for PIE devices..
mediaStorageDir.delete();
mediaStorageDir.mkdirs();
galleryAddPic(mediaStorageDir);
return (getOutputMediaFile());
}
}
和其他方法
public static int getQualityNumber(Bitmap bitmap) {
int size = bitmap.getByteCount();
int percentage = 0;
if (size > 500000 && size <= 800000) {
percentage = 15;
} else if (size > 800000 && size <= 1000000) {
percentage = 20;
} else if (size > 1000000 && size <= 1500000) {
percentage = 25;
} else if (size > 1500000 && size <= 2500000) {
percentage = 27;
} else if (size > 2500000 && size <= 3500000) {
percentage = 30;
} else if (size > 3500000 && size <= 4000000) {
percentage = 40;
} else if (size > 4000000 && size <= 5000000) {
percentage = 50;
} else if (size > 5000000) {
percentage = 75;
}
return percentage;
}
和
void galleryAddPic(File f) {
Intent mediaScanIntent = new Intent(
"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}