我使用了所有标准网络相关代码来获取约45KB to 75KB
的图像,但所有这些代码都失败了这些方法适用于大约3-5KB
图像大小的文件。如何实现45 - 75KB
的下载图像,以便在我的网络操作中在Android上的ImageView上显示它我已经使用过的东西
final URL url = new URL(urlString);
final URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(true);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
和我使用的第二个选项是::
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(urlString);
HttpResponse response = httpClient.execute(getRequest);
为什么此代码适用于较小尺寸图像而不适用于较大尺寸图像。 ?
答案 0 :(得分:7)
您下载的图片大小非常无关紧要。它使用BitmapFactory.decodeStream解码的大小是您处理图像所需的内存。 因此,重新采样可能很有用。
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH);
if(options.outHeight * options.outWidth >= 200*200){
// Load, scaling to smallest power of 2 if dimensions >= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / TARGET_HEIGHT
: options.outWidth / TARGET_WIDTH;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(sUrl);
Bitmap img = BitmapFactory.decodeStream(is, null, options);
is.close();
答案 1 :(得分:2)
很高兴看到您使用哪种代码将响应解码为位图。无论如何,尝试使用像这样的BufferedInputStream:
public Bitmap getRemoteImage(final URL aURL) {
try {
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "Oh noooz an error...");
}
return null;
}