【发布时间】:2015-11-19 09:39:32
【问题描述】:
好吧,伙计们需要一点帮助,所以我有一个应用程序可以从内存中创建位图图像并将其显示为图像视图,我按照 android 开发人员指南进入了这个阶段,因此它具有图像缩放、兑现等等,但现在我想用来自网站的图像替换内存中的图像,这是我当前的代码
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight){
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
这是我发现的一些从 url 制作图像的代码
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
我想知道如何在我现有的代码中实现这一点,以便在将图像加载到内存中之前将图像缩放到正确的分辨率以适合我的 imageView,并将 inJustDecodeBounds 设置为 true 以避免出现 outOfMemory 异常或不再存在任何异常需要这样做
【问题讨论】:
-
首先回收所有的位图。其次,一旦您从服务器获得图像,将其存储在位图中,现在压缩此位图比例等并回收前一个。一般来说,我们从服务器获取的图像并不重。