2013-06-23 41 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