我正在尝试将RelativeLayout
另存为bitmap
并将其插入到图库中,下面的代码将引发此异常:
java.lang.NullPointerException
at java.io.File.<init>(File.java:282)
at maa.Fragements.ColorPaletteFragment.galleryAddPic(ColorPaletteFragment.java:344)
因为imagePath
方法的参数galleryAddPic
为空或空
将图片插入图库:
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
保存图像:
@SuppressLint("StaticFieldLeak")
public class saveViewAsBitmap extends AsyncTask<RelativeLayout, String, String> {
@SuppressLint("SetTextI18n")
@Override
protected void onPreExecute() {
super.onPreExecute();
txt.setText("Saving image to gallery ...");
}
@Override
protected String doInBackground(RelativeLayout... relatives) {
String savedImagePath = null;
String imageFileName = "inColor" + System.currentTimeMillis() + ".png";
Bitmap image = getBitmapFromView(relatives[0]);
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/inColor Folder");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
dialogLoading.dismiss();
}
return savedImagePath;
}
@Override
protected void onPostExecute(String path) {
super.onPostExecute(path);
galleryAddPic(path);
}
}
有人可以帮助我解决此问题吗?
答案 0 :(得分:1)
确保您拥有
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在清单文件中