Android 从库中拾取图像花费的时间太长
在我的应用程序中,用户可以单击一个图像按钮,然后从gallery中选择一个图像,然后将该图像设置为图像按钮。但问题是,对于大小为5MB或更大的图像,从多媒体资料返回到我的活动需要很长时间,屏幕会变黑几秒钟。我没有对所选图像进行任何操作,我只想按用户获取所选图像的路径 似乎无法在异步任务内完成图像拾取。那么,我们如何处理大图像的图像拾取过程呢 当我从logcat中的图库中选择一个大图像时,我收到 应用程序可能在其主线程上做了太多工作Android 从库中拾取图像花费的时间太长,android,image-processing,android-asynctask,android-imagebutton,Android,Image Processing,Android Asynctask,Android Imagebutton,在我的应用程序中,用户可以单击一个图像按钮,然后从gallery中选择一个图像,然后将该图像设置为图像按钮。但问题是,对于大小为5MB或更大的图像,从多媒体资料返回到我的活动需要很长时间,屏幕会变黑几秒钟。我没有对所选图像进行任何操作,我只想按用户获取所选图像的路径 似乎无法在异步任务内完成图像拾取。那么,我们如何处理大图像的图像拾取过程呢 当我从logcat中的图库中选择一个大图像时,我收到 应用程序可能在其主线程上做了太多工作 图像拾取不能在异步任务内完成。但从图像文件/Uri解码位图肯定可
图像拾取不能在异步任务内完成。但从图像文件/Uri解码位图肯定可以在异步任务中完成
此外,由于您在ImageButton中使用图像,因此可能不需要使用全尺寸图像。使用选项InsampleSize减小解码位图的大小。正如Nabin所回答的,您可以在异步任务中进行图像处理,我为您创建了一个小示例:
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();
}
}
}
在后台工作可以防止应用程序冻结。我甚至可以非常快地选择60 MB以上大小的图像。我只想按用户获取所选图像的路径-没有路径。除此之外,请提供一个。你能告诉我们你在onActivityResult中尝试做什么吗,如果你使用它的话?我需要一个例子,它帮助了我。