package com.xjrsoft.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class PictureUtil {

    public static byte[] convertBufferedImageToByteArray(BufferedImage image) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "JPEG", baos);
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 旋转照片
     *
     * @return
     */
    public static BufferedImage rotatePhonePhoto(BufferedImage image, int orientation) {
        int angle = 0;
        // 原图片的方向信息
        if (6 == orientation) {
            //6旋转90
            angle = 90;
        } else if (3 == orientation) {
            //3旋转180
            angle = 180;
        } else if (8 == orientation) {
            //8旋转90
            angle = 270;
        } else {
            // 不旋转，直接返回
            return image;
        }

        BufferedImage src;
        src = image;
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);

        int swidth = src_width;
        int sheight = src_height;

        if (angle == 90 || angle == 270) {
            swidth = src_height;
            sheight = src_width;
        }

        Rectangle rect_des = new Rectangle(new Dimension(swidth, sheight));

        BufferedImage res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();

        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angle), src_width / 2, src_height / 2);

        g2.drawImage(src, null, null);

        return res;

    }
}
