package com.inspect.base.core.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

public class ImageCompressUtil {
    public static InputStream scaleImage(InputStream inputStream, int maxWidth) {
        try {
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width < maxWidth) {
                return inputStream;
            } else {
                width = 640;
                height = 512;
                Image image = bufferedImage.getScaledInstance(width, height, 16);
                BufferedImage outputImage = new BufferedImage(width, height, 1);
                Graphics graphics = outputImage.getGraphics();
                graphics.drawImage(image, 0, 0, (ImageObserver) null);
                graphics.dispose();
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
                ImageIO.write(bufferedImage, "jpg", imOut);
                return new ByteArrayInputStream(bs.toByteArray());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
