zetbaitsu / Разрешение компрессора не работает - PullRequest
0 голосов
/ 03 марта 2020

Поэтому я использую библиотеку zetbaitsu / Compressor для сжатия изображений и изменения размера изображения, но когда я пытаюсь сжать размер изображения исходного размера (3503 x 5254), результат для следующего значения высоты будет следующим:

800 700 600 даст разрешение (876 x 1314), которое составляет 1/8 от исходного размера, и

, если значение равно 900+, разрешение изображения (1752 x2627), которое составляет 1/2 от оригинал.

Так есть ли способ изменить размер точно в соответствии с нашими стандартами, когда я попробовал другой подобный вопрос, я не смог получить желаемые результаты.

1 Ответ

1 голос
/ 03 марта 2020

Это на самом деле возможно только путем создания собственного пользовательского ограничения для этой библиотеки. Обычное ограничение разрешения этой библиотеки ( Methodcall ) ( Объявление метода ) использует следующий метод ( найден здесь ):

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

Таким образом, он уменьшает размер изображения на 2, если он больше требуемого размера.

Самый простой способ изменить это, вероятно, создать собственное пользовательское ограничение и изменить вызов calculateInSampleSize() на свой. собственный метод вычисления модификатора для точного размера.

Редактировать: Это примерное ограничение, как оно должно работать. Я пока не могу проверить, но это должно дать вам представление о том, как это работает:

    public class SizeContstraint implements Constraint
    {

        private int _height;

        // Resulting image height
        public SizeContstraint(int height)
        {
            _height = height;
        }

        // Checks, if the constraint is valid
        @Override
        public boolean isSatisfied(@NotNull final File file)
        {
            // Get the file options (height, width, e.t.c)
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            // Calculate if the current image is bigger than the necessary size
            return calculateExactSizeModifier(options, _height) > 1;
        }

        // This method is only called, if the constraint is invald (the image is too big)
        @NotNull
        @Override
        public File satisfy(@NotNull final File file)
        {
            int height = _height;
            int width = 0;

            // Get the file options (height, width, e.t.c)
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            // Get the size modifier to be able to resize the image
            int modifier = calculateExactSizeModifier(options, height);

            // Calculate the width using the modifier
            width = options.outWidth / modifier;

            // Resize the file into a bitmap
            Bitmap bmp = id.zelory.compressor.UtilKt.decodeSampledBitmapFromFile(file, width, height);
            // Write the bitmap back into the file
            return id.zelory.compressor.UtilKt.overWrite(file, bmp, Bitmap.CompressFormat.JPEG, 100);
        }

        private int calculateExactSizeModifier(BitmapFactory.Options options, int reqHeight)
        {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int modifier = 1;

            // Calculate modifier if height bigger than requested height
            if (height > reqHeight)
            {
                modifier = height / reqHeight;
            }

            return modifier;
        }
    }

...