2011-11-18 119 views
0

當我從網上下載圖片,並將它們保存到SD卡在我的應用程序,我用下面的方法:下載圖像:圖像質量影響

private void saveImageToSDcard() throws IOException { 
     File sdImageMainDirectory = new File(
       Environment.getExternalStorageDirectory(), getResources() 
         .getString(R.string.directory)); 
     if (!sdImageMainDirectory.exists()) { 
      sdImageMainDirectory.mkdirs(); 
     } 

     for (int i = 0; i < jArray.length(); i++) { 
      reviewImageLink = url[i]; 

      urlimage = new URL(reviewImageLink); 
      input = urlimage.openStream(); 

      try { 
       output = new FileOutputStream(
         Environment.getExternalStorageDirectory() 
           + "/Downloads/" + "photo" + i + ".jpg"); 
       try { 
        byte[] buffer = new byte[2]; 
        int bytesRead = 0; 
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
         output.write(buffer, 0, buffer.length); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 

        output.close(); 

       } 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } finally { 

       input.close(); 

      } 
     } 

    } 

的圖像保存到SD卡當我嘗試將SD卡中的圖像放入我的應用程序中,有時圖像看起來模糊不清。這不會一直髮生,但是當它發生時,部分圖像很不清楚。什麼會造成這種情況?

重要:我用下面的緩衝區從URL中讀取輸入流:

byte[] buffer = new byte[2]; 

我發現,如果我增加它的大小,然後將其保存到SD卡的圖像是完全模糊。

回答

1

你應該只寫入你讀的字節數,其餘的緩衝區是零或垃圾。使用幾K的緩衝液(比如,2048或4096),並改變你寫的呼籲:

output.write(buffer, 0, bytesRead); 
0

當您創建位圖並在應用程序中使用它時查看代碼。這裏改變其大小等屬性會影響質量。

1

更改while循環,如下所示:

while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
    output.write(buffer, 0, bytesRead); 
} 

因爲read可能無法讀取儘可能多字節作爲您的緩衝區大小。也可以使用更大的緩衝區大小(如100 * 1024),這不應影響圖像質量,但應提高性能。

編輯
關於模糊的圖像,你是否在任何地方調整圖像大小?這會造成模糊。

+0

不,我不調整圖像大小。我認爲這個output.write(buffer,0,bytesRead); 解決了這個問題 – Gabrielle

1

我對Android開發只是一個初學者很新,但我一直在嘗試這一段時間,並在我的代碼中設置位圖選項,然後得到位圖,這似乎爲我工作,也許這將幫你。事情是這樣的:

BitmapFactory.Options opt = new BitmapFactory.Options(); 
opt.inScaled = false; 
opt.inSampleSize = 1;     
opt.inDither = true; 

//Use inPreferQualityOverSpeed option with 2.3.3+ 
if (android.os.Build.VERSION.SDK_INT >= 10) 
     opt.inPreferQualityOverSpeed = true; 

然後,我用它來從一個數組索引讓我的位圖,並告訴它使用的選項:

mBitmap = BitmapFactory.decodeResource(getResources(), mImageIds[image_index], opt); 

使用此代碼,這些位圖選項似乎給我爲我想要寫入外部存儲的圖像提供最佳的圖像質量。