【问题标题】:What is the fastest way to compress image to a specified size?将图像压缩到指定大小的最快方法是什么?
【发布时间】:2018-04-25 07:54:16
【问题描述】:

在我的项目中,有时我需要将一些图像(1-10)上传到服务器。大小从1M到10M不等。上传前,每张图片应压缩到

public static byte[] compressImageA(Bitmap image, int maxSize) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int options = 100;
    image.compress(Bitmap.CompressFormat.JPEG, options, baos);
    while (baos.size() / 1024 > maxSize) {
        baos.reset();
        options -= 10;
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    if (image != null && !image.isRecycled()) {
        try {
            image.recycle();
        } catch (Exception e) {
        }
    }
    return baos.toByteArray();
}

这个方法可以,但速度不够快。例如,压缩10张图片大约需要25秒。(每张的大小在1M到10M之间)。经过一些测试,我发现Bitmap.compress()可能会被调用很多次并且在压缩过程中花费的时间最多。那么我该怎么做才能让它更快呢?我希望Bitmap.compress()在每次压缩过程中只被调用一次。或者有没有其他方法可以更快地将图像压缩到指定的大小?

【问题讨论】:

  • 你找到解决办法了吗?
  • @PPV 不幸的是。不。

标签: android image-compression


【解决方案1】:

您可以使用此方法从实际尺寸减小尺寸

/**
     * reduces the size of the image
     *
     * @param image  uncompressed image
     * @param reduce how much to reduce
     * @return new bitmap
     */
    public static Bitmap reduceBitmap(Bitmap image, int reduce) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width -= reduce;
            height = (int) (width / bitmapRatio);
        } else {
            height -= reduce;
            width = (int) (height * bitmapRatio);
        }
        if (width > 0 && height > 0)
            return Bitmap.createScaledBitmap(image, width, height, true);
        else
            return image;
    }

或者您可以根据需要使用以下代码,我将其用于 PNG 您可以检查其他代码

Bitmap actualImage=BitmapFactory.decodeStream(getAssets().open("imagg1.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
actualImage.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

【讨论】:

    【解决方案2】:

    您的算法几乎是最快的。

    是时候开始跳出框框思考了。 25 秒内 10 张图像意味着 1 张图像需要 2.5 秒。你希望它有多快?幸运的是,该算法很容易并行化。因此,您可以将任务拆分到 n 台计算机上。

    【讨论】:

    • 这家伙需要一个算法,而不是解释。你认为如何将它与所有安卓手机并行?
    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多