package epson.print.Util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class bmpScaler {
    private Bitmap scaled;

    private static class Size {
        int sample;
        float scale;

        private Size() {
        }
    }

    public bmpScaler(String str, int i, boolean z) throws IOException {
        FileInputStream fileInputStream;
        FileInputStream fileInputStream2 = null;
        FileInputStream fileInputStream3 = new FileInputStream(str);
        Size roughSize = getRoughSize(fileInputStream3, i);
        fileInputStream = new FileInputStream(str);
        roughScaleImage(fileInputStream, roughSize);
        if (!z) {
            scaleImage(i);
        }
        fileInputStream.close();
        fileInputStream.close();
    }

    public Bitmap getScaled() {
        return scaled;
    }

    private void scaleImage(int i) {
        int width = scaled.getWidth();
        int height = scaled.getHeight();
        float f = (float) i;
        float f2 = f / ((float) width);
        float width2 = ((float) scaled.getWidth()) / f;
        float f3 = (float) height;
        Matrix matrix = new Matrix();
        matrix.postScale(f2, ((float) ((int) (f3 / width2))) / f3);
        scaled = Bitmap.createBitmap(this.scaled, 0, 0, width, height, matrix, true);
    }

    private void roughScaleImage(InputStream inputStream, Size size) {
        new Matrix().postScale(size.scale, size.scale);
        BitmapFactory.Options options = new BitmapFactory.Options();
        while (true) {
            try {
                options.inSampleSize = size.sample;
                scaled = BitmapFactory.decodeStream(inputStream, (Rect) null, options);
                return;
            } catch (OutOfMemoryError unused) {
                size.sample *= 2;
            }
        }
    }

    private Size getRoughSize(InputStream inputStream, int i) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream, (Rect) null, options);
        return getRoughSize(options.outWidth, options.outHeight, i);
    }

    private Size getRoughSize(int i, int i2, int i3) {
        Size size = new Size();
        size.scale = (float) (i / i3);
        size.sample = 1;
        int i4 = (int) (((float) i2) / size.scale);
        while (true) {
            i /= 2;
            if (i < i3 || (i2 = i2 / 2) < i4) {
                return size;
            }
            size.sample *= 2;
        }
    }
}
