在我的参考活动中,我使用以下代码从用户选择创建位图:
Uri selectedImage = imageReturnedIntent.getData(); // uri from user selection.
File tempFile; // temporary File
Uri tempUri; // temporary Uri
try
{
// initializing File
tempFile = File.createTempFile("crop", "png", Environment.getExternalStorageDirectory());
}
catch (IOException e1)
{
tempFile = null;
}
if(tempFile != null)
{
// initializing Uri
tempUri = Uri.fromFile(tempFile);
}
else
{
tempUri = selectedImage;
}
// creating new crop intent
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setData(selectedImage); // original image Uri
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("aspectX", width);
intent.putExtra("aspectY", height);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", tempUri); // cropped image Uri
intent.putExtra("outputFormat", "PNG");
startActivityForResult(intent, 23);
InputStream imageStream;
Bitmap yourSelectedImage;
try
{
// initializing InputStream
imageStream = getContentResolver().openInputStream(tempUri);
}
catch (FileNotFoundException e)
{
imageStream = null;
}
if(imageStream != null)
{
// getting Bitmap from Uri
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
}
else
{
yourSelectedImage = null;
}
然后在我的其他活动中,我尝试检索这个裁剪的图像并绘制它。但它始终显示为 null 并绘制默认位图。
这是检索部分:
File tempF = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "crop.png"); // also tried using only "crop" as filename.
Uri uri = Uri.fromFile(tempF);
InputStream imageStream;
Bitmap yourSelectedImage;
try
{
imageStream = getContentResolver().openInputStream(uri);
}
catch (FileNotFoundException e)
{
imageStream = null;
}
if(imageStream != null)
{
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
}
else
{
yourSelectedImage = null;
}
if(yourSelectedImage == null)
{
drawable = BitmapFactory.decodeResource(getResources(),R.drawable.bg); // bg is default bitmap if image is not found.
}
else
{
drawable = yourSelectedImage;
}
// *all drawing happens here*
tempF.delete();