0
在我正在開發的應用程序中,我想從URL下載圖像(jpeg)並顯示它。我到目前爲止的代碼已經工作,但我不明白對於同一張圖片怎麼可能,一段時間需要3秒才能解碼,另一段需要200秒。這是我的代碼:Android:檢索並解碼JPEG
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);
}
我正在嘗試使用多個圖像,但最大有1,332,828字節(1.3MB)和1536×2048像素。正如我之前所說的,有時它會在3到5秒內解碼,而其他解碼需要很長時間。我總是使用相同的option.inSampleSize
。
我在之前的另一個項目中使用了相同的代碼,使用較大的圖像,它工作正常。唯一不同的是,我從文件中而不是從URL中檢索inputStream,但顯然,除了下載時間之外,我認爲這沒什麼區別。
我檢查了第一次解碼以獲取文件的尺寸需要2或3秒,所以這不是問題。我正在測試Nexus 4,因此它與設備性能無關。我只是不知道爲什麼大部分時間需要這麼長時間,還有幾次它可以正常工作。
感謝您的幫助!
這是wifi,但我說的是處理時間,一旦下載完成。 – mario595