我正在开发一个应用程序,允许用户从图库中选择一张图片,然后我开始一项活动来裁剪它。
我想将裁剪的图像发送回调用活动。
这两项活动都扩展了AppCompatActivity。
致电活动:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// start image crop activity
String dataString = data.getDataString();
Intent intent=new Intent(this, CropPhotoActivity.class);
intent.putExtra("SELECTED_PICTURE_FOR_CROP", dataString);
startActivityForResult(intent, CROP_PICTURE);
}
else if(requestCode == CROP_PICTURE) {
// get cropped bitmap
Bitmap bitmap = (Bitmap) data.getParcelableExtra("CROPPED_IMAGE");
profilePhoto.setImageBitmap(bitmap);
}
}
}
在裁剪图像活动中,我有一个按钮,点击该按钮应该返回到调用活动:
Button okButton = (Button)findViewById(R.id.ok_button);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE", cropped_bitmap);
setResult(RESULT_OK, returnIntent);
finish(); // sometimes restarts app
}
});
有时候位图会被正确地返回,而有时却没有,并且应用程序会重新启动而不会出错。为什么会这样? putExtra与位图大小或其他任何事情有关吗?
答案 0 :(得分:0)
您可以尝试替换
AppcompatActivity.this.finish()
(AppcompatActivity是您的班级名称)
有:
finish(); // sometimes restarts app
或者,在调用Activity:
中创建一个方法public static void cropComplete(Activity activity)
{
activity.startActivity(activity, AnotherActivity.class);
activity.finish();
}
答案 1 :(得分:0)
Theres是在意图中作为额外传递的数据长度的限制。尽量不要传递dataString值;相反,您应该将图像保存为临时文件,在intent中传递路径,然后从调用活动中加载图像(或者您可以将dataString保存在静态帮助器类中)。
在裁剪活动中(从Save bitmap to location保存位图代码):
// Save bitmap
String filename = "tempImage.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Get image file path
String path = dest.getAbsolutePath();
// Set result with image path
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE_PATH", path);
setResult(RESULT_OK, returnIntent);
finish();
在来电者活动中:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CROP_PICTURE) {
// Get image file path
String imagePath = data.getStringExtra("CROPPED_IMAGE_PATH");
// Load image
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}