java以正确的方式从url加载位图
好了,伙计们需要一些帮助,所以我有一个应用程序,可以从内存中创建位图图像,并将其显示为图像视图,我按照安卓开发者的指导原则达到了这个阶段,所以它有图像缩放、兑现等功能,但现在我想用一个网站上的图像替换内存中的图像,这是我当前的代码
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;
}
}
我想知道如何在我现有的代码中实现这一点,以便在将inJustDecodeBounds设置为true的情况下加载到内存之前,将图像缩放到合适的分辨率以适合我的imageView,从而避免outOfMemory异常,或者不再需要这样做
# 1 楼答案
如果你想在网上做这件事,我建议你使用volley imageLoader,你使用的代码正在下载。我建议你在开始之前做一些研究,虽然这和你通常做的有点不同,但一旦你得到它,图像加载只需要几行。另一方面,如果你还想下载它,把它改成位图,直接从文件中读取。此外,从存储器中显示图像不需要太多工作,下面是一个示例
http://blog.lemberg.co.uk/volley-part-3-image-loader