2013-06-23 218 views
3

我用安卓相機拍了一張照片。結果是一個字節數組。我通過將它寫在SD卡上(FileOutputStream)來保存它。結果是具有近3mb的文件大小的圖像。我想減少這個文件大小,所以壓縮圖像。減少圖像的文件大小

如果在將字節數組寫入輸出流之前可以減少文件大小,那將會很好。這是可能的還是我必須先保存它?

+1

後壓縮的圖像您碼。 – Blackbelt

+0

哪部分代碼?這是保存圖片的代碼:FileOutputStream outStream = null; 嘗試outStream = new FileOutputStream(「/ sdcard/Image.jpg」);outStream.write(data); outStream.close(); ... – JavaForAndroid

回答

5

我通常調整從而降低它的大小的圖像

Bitmap bitmap = resizeBitMapImage1(exsistingFileName, 800, 600); 

您也可以使用此代碼

ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

//you can create a new file name "test.jpg" in sdcard folder. 
File f = new File(Environment.getExternalStorageDirectory() 
         + File.separator + "test.jpg") 
f.createNewFile(); 
//write the bytes in file 
FileOutputStream fo = new FileOutputStream(f); 
fo.write(bytes.toByteArray()); 

// remember close de FileOutput 
fo.close(); 

調整大小碼

public static Bitmap resizeBitMapImage1(String filePath, int targetWidth, int targetHeight) { 
    Bitmap bitMapImage = null; 
    try { 
     Options options = new Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(filePath, options); 
     double sampleSize = 0; 
     Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth 
       - targetWidth); 
     if (options.outHeight * options.outWidth * 2 >= 1638) { 
      sampleSize = scaleByHeight ? options.outHeight/targetHeight : options.outWidth/targetWidth; 
      sampleSize = (int) Math.pow(2d, Math.floor(Math.log(sampleSize)/Math.log(2d))); 
     } 
     options.inJustDecodeBounds = false; 
     options.inTempStorage = new byte[128]; 
     while (true) { 
      try { 
       options.inSampleSize = (int) sampleSize; 
       bitMapImage = BitmapFactory.decodeFile(filePath, options); 
       break; 
      } catch (Exception ex) { 
       try { 
        sampleSize = sampleSize * 2; 
       } catch (Exception ex1) { 

       } 
      } 
     } 
    } catch (Exception ex) { 

    } 
    return bitMapImage; 
} 
+0

我知道這種壓縮方式。但是,我如何獲得位圖作爲字節數組的結果? – JavaForAndroid

+0

stream.toByteArray() – MDMalik

+0

@JavaForAndroid是否解決了您的問題 – MDMalik