Android:检索和解码JPEG



在我正在开发的应用程序中,我想从URL下载一个图像(jpeg)并显示它。到目前为止,我已经完成了代码,但我不明白为什么对于同一个图像,一段时间需要3秒才能解码,另一段时间则需要200秒。这是我的代码:

String attachmentUrl = attachment.getContentSrc();
long mills = System.currentTimeMillis();
//Get the stream from the URL
InputStream is = new BufferedInputStream(new URL(attachmentUrl).openConnection().getInputStream());
is.mark(attachment.getFileSize());
Log.d("AttachmentsUtils","Downloading Time: "+((System.currentTimeMillis()-mills)/1000)+" secs");
mills = System.currentTimeMillis();
BitmapFactory.Options options = new BitmapFactory.Options();
//Now, we only want the size of the image
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
//Calculate the sampleSize
options.inSampleSize = calculateInSampleSize(options, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
options.inJustDecodeBounds = false;
//Reset the stream in order to decode it again, but this time, we will get the bitmap
is.reset();
Bitmap bm = BitmapFactory.decodeStream(is, null, options);
Log.d("AttachmentsUtils","Decode Time: "+((System.currentTimeMillis()-mills)/1000)+" secs. With sample "+options.inSampleSize);
//Return an scaled version of the bitmap
if(bm!=null){
return Bitmap.createScaledBitmap(bm, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, false);
}

我尝试了几个图像,但最大的有1332828字节(1.3MB)和1536×2048像素。正如我之前所说,有时它在3或5秒内解码,有时解码需要很长时间。我总是使用相同的option.inSampleSize

我以前在另一个项目中使用过同样的代码,使用了更大的图像,效果很好。唯一不同的是,我从文件中检索inputStream,而不是从URL中检索,但显然,除了下载时间之外,我认为这没有任何区别。

我已经检查过了,获得文件尺寸的第一次解码大约需要2或3秒,所以这不是问题所在。我正在测试Nexus 4,所以它与设备性能无关。我只是不知道为什么大多数时候需要这么长时间,而有些时候效果很好。

谢谢你的帮助!

您是通过移动网络还是无线网络进行下载。如果你使用3G,我一点也不会惊讶于看到文件下载和处理所需的时间有很大差异。

最新更新