我有 7 个小图像按钮。我希望当您单击一个时,您可以从图库中选择一张图片并将其显示在按钮上。问题出在像 4.5 Mb 这样的大图片上,我添加的每张图片都占用 50 Mb 内存,而在第三张图片上,它因内存不足而崩溃。当我删除按钮上的 setImage
时,我只保存我的图片供以后使用。
private void setPicture(ImageButton button, Intent data){
Uri imageUrl = data.getData();
InputStream inputStream = null;
ByteArrayOutputStream stream = null;
try {
inputStream = getContentResolver().openInputStream(imageUrl);
Bitmap image = BitmapFactory.decodeStream(inputStream);
Drawable drawable = new BitmapDrawable(getResources(), image);
stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
pictures.add(stream.toByteArray());
//button.setImageDrawable(drawable);
最佳答案
您应该避免将完整的大位图保存在内存中,只是为了在按钮上显示它的一小部分样本——而是加载一个缩减采样的版本。
您应该查看这份官方 Android 指南:
高效加载大型位图
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
关于android - 在图像按钮上显示图库中的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36009913/