/*
 * Decompiled with CFR 0.152.
 * 
 * Could not load the following classes:
 *  com.sun.image.codec.jpeg.JPEGCodec
 *  com.sun.image.codec.jpeg.JPEGImageEncoder
 */
package com.hst.common.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;

public class ImgCompress {
    private Image img;
    private int width;
    private int height;

    public ImgCompress(String fileName) throws IOException {
        File file = new File(fileName);
        this.img = ImageIO.read(file);
        this.width = this.img.getWidth(null);
        this.height = this.img.getHeight(null);
    }

    public ImgCompress(byte[] imgsByte) throws IOException {
        ByteArrayInputStream buffin = new ByteArrayInputStream(imgsByte);
        this.img = ImageIO.read(buffin);
        this.width = this.img.getWidth(null);
        this.height = this.img.getHeight(null);
    }

    public byte[] resizeFix(int w, int h) throws IOException {
        if (this.width / this.height > w / h) {
            return this.resizeByWidth(w);
        }
        return this.resizeByHeight(h);
    }

    public byte[] resizeByWidth(int w) throws IOException {
        int h = this.height * w / this.width;
        return this.resize(w, h);
    }

    public byte[] resizeByHeight(int h) throws IOException {
        int w = this.width * h / this.height;
        return this.resize(w, h);
    }

    public byte[] resize(int w, int h) throws IOException {
        BufferedImage image = new BufferedImage(w, h, 1);
        image.getGraphics().drawImage(this.img, 0, 0, w, h, null);
        ByteArrayOutputStream outp = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder((OutputStream)outp);
        encoder.encode(image);
        return outp.toByteArray();
    }
}
