3

我用安卓相机拍了一张照片。结果是一个字节数组。我通过将其写入 sdcard (FileOutputStream) 来保存它。结果是一个文件大小接近 3mb 的图像。我想减小这个文件大小,所以压缩图像。

如果可以在我将字节数组写入输出流之前减小文件大小,那就太好了。这是可能的还是我必须先保存它?

4

1 回答 1

6

我通常调整图像的大小以减小它的大小

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;
}
于 2013-06-23T11:03:57.340 回答