android – 减少图像的文件大小

我用android相机拍了照片.结果是一个字节数组.我通过在sdcard(FileOutputStream)上写它来保存它.结果是文件大小接近3mb的图像.我想减少这个文件大小,所以压缩图像.

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

解决方法:

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

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;
}
上一篇:linux – 在文本文件中重新排序行以获得更好的压缩比


下一篇:c# – 这是否可以压缩带有zip库的JPEG文件