我需要将高分辨率远程图像加载到imageview,但不使用任何外部库或框架。图像类似于2150x1500像素,这是我的加载代码:
URL imageUrl = new URL(url);
HttpURLConnection connection;
if (url.startsWith("https://")) {
connection = (HttpURLConnection) imageUrl.openConnection();
} else {
connection = (HttpURLConnection) imageUrl.openConnection();
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(f);
CacheUtils.CopyStream(is, os);
os.close();
image = decodeFile(f);
img.setImageBitmap(image);
这里是decodeFile函数:
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
我总是得到纹理大小太大的异常。有没有办法加载这些图像?或者有没有办法调整图像大小2或4次,但调整大小以适应2048像素宽?
答案 0 :(得分:0)
class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
@Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
@Override
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(Bitmap.createScaledBitmap(result, 120, 120, false));
}
}
指定所需的高度和宽度,而不是120。
在你的oncreate中调用它
new DownloadImage((ImageView) findViewById(R.id.imageView1))
.execute("https://.........");