package com.izouma.awesomeadmin.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;

public class ImagesUtil {

    //base64字符串转化成图片

    /**
     * <p>base64字符串转化成图片流。</p>
     *
     * @param imgStr
     * @return
     */
    public static InputStream GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片

        if (imgStr == null) //图像数据为空
            return null;
        imgStr = imgStr.substring(imgStr.indexOf(',') + 1);

        try {
            //Base64解码
            // byte[] b = Base64.getDecoder().decode(imgStr);
            byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            InputStream sbs = new ByteArrayInputStream(b);
            //生成jpeg图片
            //            out.write();
            //            out.flush();
            //            out.close();
            //            //生成jpeg图片
            //            InputStream in = null;
            return sbs;
        } catch (Exception e) {
            return null;
        }
    }

    public static InputStream compress(InputStream inputStream, int maxWidth, int maxHeight) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            int orientation = 1;
            Image img = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
            Metadata metadata = null;
            try {
                metadata = JpegMetadataReader.readMetadata(new ByteArrayInputStream(baos.toByteArray()));
                ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
                orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
            } catch (JpegProcessingException e) {
                e.printStackTrace();
            } catch (MetadataException e) {
                e.printStackTrace();
            }

            double scale = 1;
            int width = img.getWidth(null);
            int height = img.getHeight(null);
            if (!(width < maxWidth && height < maxHeight)) {
                if (width / height > maxWidth / maxHeight) {
                    scale = maxWidth / (double) width;
                } else {
                    scale = maxHeight / (double) height;
                }
            }
            int newWidth, newHeight;
            BufferedImage bufferedImage;
            Graphics2D graphics;
            switch (orientation) {
                case 6:
                    newHeight = (int) (width * scale);
                    newWidth = (int) (height * scale);
                    bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                    graphics = bufferedImage.createGraphics();
                    graphics.rotate(Math.toRadians(90), 0, 0);
                    graphics.translate(0, -height * scale);
                    break;
                case 8:
                    newHeight = (int) (width * scale);
                    newWidth = (int) (height * scale);
                    bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                    graphics = bufferedImage.createGraphics();
                    graphics.rotate(Math.toRadians(-90), 0, 0);
                    graphics.translate(-width * scale, 0);
                    break;
                case 3:
                    newWidth = (int) (width * scale);
                    newHeight = (int) (height * scale);
                    bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                    graphics = bufferedImage.createGraphics();
                    graphics.rotate(Math.toRadians(180), 0, 0);
                    graphics.translate(-width * scale, -height * scale);
                    break;
                default:
                    newWidth = (int) (width * scale);
                    newHeight = (int) (height * scale);
                    bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                    graphics = bufferedImage.createGraphics();
                    break;
            }
            graphics.drawImage(img.getScaledInstance((int) (width * scale), (int) (height * scale), Image.SCALE_SMOOTH), 0, 0, null);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(bufferedImage);
            out.close();

            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}
