在我的应用程序用户可以单击图像按钮,然后从库中选择一个图像,然后该图像设置为图像按钮。但问题是,对于尺寸为5MB或更大尺寸的图像,从图库回到我的活动需要很长时间,屏幕会变黑并持续几秒钟。我不对所选图像进行任何操作,我只想让用户获取所选图像的路径。
似乎无法在AsyncTask中完成图像拾取。那么我们如何处理大图像的图像拾取过程呢。
当我在logcat中从画廊中选择一个大图像时,我收到了
应用程序可能在其主线程上做了太多工作。
答案 0 :(得分:1)
可能无法在AsyncTask
内完成图片选取。但是,从图像文件/ Uri中解码位图肯定可以在AsyncTask
中完成。
此外,由于您在ImageButton
中使用图像,因此您可能不需要使用全尺寸图像。使用Options#inSampleSize
减小解码位图的大小。
答案 1 :(得分:0)
Nabin回答说,您可以在AsyncTask
中进行图像处理,我为您创建了一个小例子:
public class MainActivity extends AppCompatActivity {
public static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE) {
Uri imagePath = data.getData();
new LoadImageDataTask(imagePath).execute();
}
}
private class LoadImageDataTask extends AsyncTask<Void, Void, Bitmap> {
private Uri imagePath;
LoadImageDataTask(Uri imagePath) {
this.imagePath = imagePath;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
InputStream imageStream = getContentResolver().openInputStream(imagePath);
return BitmapFactory.decodeStream(imageStream);
} catch (FileNotFoundException e) {
Toast.makeText(MainActivity.this, "The file " + imagePath + " does not exists",
Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
Toast.makeText(MainActivity.this, "I got the image data, with size: " +
Formatter.formatFileSize(MainActivity.this, bitmap.getByteCount()),
Toast.LENGTH_SHORT).show();
}
}
}
在后台进行工作,可以防止您的应用冻结。我甚至可以快速选择60MB +大小的图像。