package com.jsowell.common.util.file;

import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.util.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

/**
 * 图片处理工具类
 *
 * @author jsowell
 */
public class ImageUtils {
	private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

	public static byte[] getImage(String imagePath) {
		InputStream is = getFile(imagePath);
		try {
			return IOUtils.toByteArray(is);
		} catch (Exception e) {
			log.error("图片加载异常 {}", e);
			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) {
			log.error("获取图片异常 {}", e);
		}
		return null;
	}

	/**
	 * 读取文件为字节数据
	 *
	 * @param url 地址
	 * @return 字节数据
	 */
	public static byte[] readFile(String url) {
		InputStream in = null;
		try {
			if (url.startsWith("http")) {
				// 网络地址
				URL urlObj = new URL(url);
				URLConnection urlConnection = urlObj.openConnection();
				urlConnection.setConnectTimeout(30 * 1000);
				urlConnection.setReadTimeout(60 * 1000);
				urlConnection.setDoInput(true);
				in = urlConnection.getInputStream();
			} else {
				// 本机地址
				String localPath = JsowellConfig.getProfile();
				String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
				in = new FileInputStream(downloadPath);
			}
			return IOUtils.toByteArray(in);
		} catch (Exception e) {
			log.error("获取文件路径异常 {}", e);
			return null;
		} finally {
			IOUtils.closeQuietly(in);
		}
	}

	/**
	 * 图像压缩方法
	 * @param originalImage 源图像
	 * @param quality 压缩质量
	 * @return
	 */
	public static BufferedImage compressImage(BufferedImage originalImage, double quality) {
		BufferedImage compressedImage = null;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try {
			// 设置压缩参数
			ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
			ImageWriteParam param = writer.getDefaultWriteParam();
			param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			param.setCompressionQuality((float) quality);

			// 压缩图像
			writer.setOutput(ImageIO.createImageOutputStream(outputStream));
			writer.write(null, new IIOImage(originalImage, null, null), param);

			// 读取压缩后的图像
			ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
			compressedImage = ImageIO.read(inputStream);

			// 关闭流
			outputStream.close();
			inputStream.close();
			writer.dispose();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return compressedImage;
	}
}
