package cn.kk.spring_simple_operation.utils;

import org.apache.poi.util.IOUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;


/**
 * 图片处理工具类
 */
public class ImageUtils {

	public static byte[] getImage(String imagePath) {
		InputStream is = getFile(imagePath);
		try {
			return IOUtils.toByteArray(is);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static InputStream getFile(String imagePath) {
		try {
			byte[] result = readFile(imagePath);
			result = Arrays.copyOf(result, result.length);
			return new ByteArrayInputStream(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 读取文件为字节数据
	 *
	 * @param url 地址
	 * @return 字节数据
	 */
	public static byte[] readFile(String url) {
		InputStream in = null;
		ByteArrayOutputStream baos = null;
		try {
			// 网络地址
			URL urlObj = new URL(url);
			URLConnection urlConnection = urlObj.openConnection();
			urlConnection.setConnectTimeout(30 * 1000);
			urlConnection.setReadTimeout(60 * 1000);
			urlConnection.setDoInput(true);
			in = urlConnection.getInputStream();
			return IOUtils.toByteArray(in);
		} catch (Exception e) {
			e.getMessage();
			return null;
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(baos);
		}
	}

	/**
	 * 竖着合并多个图片
	 *
	 * @param images
	 */
	public static BufferedImage mergeImg(List<BufferedImage> images) {


		Integer width = images.stream().map(BufferedImage::getWidth).max(Integer::compareTo).orElse(0);
		Integer height = images.stream().map(BufferedImage::getHeight).reduce(Integer::sum).orElse(0);
		BufferedImage merge = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


		Graphics2D g2d = merge.createGraphics();
		g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));


		Integer tmpH = 0;
		for (BufferedImage image : images) {
			g2d.drawImage(image, 0, tmpH, image.getWidth(), image.getHeight(), null);
			tmpH += image.getHeight();
		}

		return merge;
	}

	/**
	 * 修改图片分辨率
	 *
	 * @param bufferedImage
	 * @param WIDTH
	 * @param HEIGHT
	 */
	public BufferedImage scaleImage(BufferedImage bufferedImage, int WIDTH, int HEIGHT) {
		BufferedImage bi = null;
		try {
			bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = bi.createGraphics();

			g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));

			g2d.drawImage(bufferedImage, 0, 0, WIDTH, HEIGHT, null);
		} catch (Exception e) {
			return null;
		}
		return bi;
	}

}
