android - 减小图像的文件大小

标签 android arrays image compression byte

我用安卓相机拍了张照片。结果是一个字节数组。我通过将其写入 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;
}

关于android - 减小图像的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260068/

相关文章:

c# - 如何将Dictionary <int,long>转换为字符串数组/列表?

image - Tensorflow.js:将图像调整为特定字节大小

android - 支持多个 Android 屏幕 : Advantages vs. 具有所有密度的抽屉文件夹(图像)的缺点?

android - 如何从我的 Android 应用程序中获取资源的目录列表?

android - 尝试将带有图像的表单发送到 PHP 服务器时 Android 中的内存泄漏

javascript - 根据javascript中的匹配条件从数组数组中查找匹配项

javascript - 从字符串中获取元素数组并查找值

java - 在指定目录启动 JFileChooser 并仅显示特定类型的文件

image - Internet Explorer DOM7009 : Unable to decode image at URL: [url]

安卓:ClassNotFoundException