package com.zzsn.orc;


import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.Iterator;

/**
 * 处理图片的工具类
 *
 */
public class PicUtil {
	/**
	 * 切割图片
	 *
	 * @param segPos
	 * @return
	 */
//	public BufferedImage getSegPart(List<Pixel> segPos) {
//		return null;
//	}

	/**
	 * 读取图片文件，返回字节
	 *
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public byte[] image2byte(String path) throws FileNotFoundException, IOException {
		byte[] data = null;
		FileImageInputStream input = null;
		input = new FileImageInputStream(new File(path));
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int numBytesRead = 0;
		while ((numBytesRead = input.read(buf)) != -1) {
			output.write(buf, 0, numBytesRead);
		}
		data = output.toByteArray();
		output.close();
		input.close();
		return data;
	}

	/**
	 * 读取图片字节流，返回字节
	 *
	 * @param image
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static byte[] bufferimage2byte(BufferedImage image) throws FileNotFoundException, IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		boolean flag = ImageIO.write(image, "jpg", out);
		byte[] byteImage = out.toByteArray();
		return byteImage;
	}

	public static byte[] readFileByBytes(String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(filePath);
		} else {
			ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
			BufferedInputStream in = null;

			try {
				in = new BufferedInputStream(new FileInputStream(file));
				short bufSize = 1024;
				byte[] buffer = new byte[bufSize];

				int len1;
				while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
					bos.write(buffer, 0, len1);
				}

				byte[] var7 = bos.toByteArray();
				return var7;
			} finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (IOException var14) {
					var14.printStackTrace();
				}

				bos.close();
			}
		}
	}

	/**
	 * 替换图片像素颜色
	 *
	 * @param file
	 * @param srcColor
	 * @param targetColor
	 * @param targetFile
	 * @throws IOException
	 */
	public static void replaceImageColor(String file, Color srcColor, Color targetColor, String targetFile)
			throws IOException {
		BufferedImage bi = ImageIO.read(new File(file));
		for (int i = 0; i < bi.getWidth(); i++) {
			for (int j = 0; j < bi.getHeight(); j++) {
				if (srcColor.getRGB() != bi.getRGB(i, j)) {
					bi.setRGB(i, j, targetColor.getRGB());
				}
			}
		}
		Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpg");
		ImageWriter writer = it.next();
		File f = new File(targetFile);
		ImageOutputStream ios = ImageIO.createImageOutputStream(f);
		writer.setOutput(ios);
		writer.write(bi);
		bi.flush();
		ios.flush();
		ios.close();
	}

	/**
	 * 替换图片像素颜色
	 *将不为当前的像素替换为目标像素
	 * @param srcColor
	 * @param targetColor
	 * @throws IOException
	 */
	public static BufferedImage replaceImageColor(BufferedImage bi, Color srcColor, Color targetColor)
			throws IOException {
		for (int i = 0; i < bi.getWidth(); i++) {
			for (int j = 0; j < bi.getHeight(); j++) {
				if (srcColor.getRGB() == bi.getRGB(i, j)) {
					bi.setRGB(i, j, targetColor.getRGB());
				}
			}
		}
		return bi;
	}

	public static BufferedImage img_tailor(BufferedImage src, int x, int y, int width, int height) {
		BufferedImage back=null;
		if(src.getHeight() > (y+height)&y>0){
		  back = src.getSubimage(x, y, width, height);
		}
		return back;
	}

	/**
	 * 读取图片
	 *
	 * @param imgpath
	 * @return
	 */
	public static BufferedImage file2img(String imgpath) {
		try {
//			System.out.println(imgpath);
			BufferedImage bufferedImage = ImageIO.read(new File(imgpath));
			return bufferedImage;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 图片写为文件
	 *
	 * @param img
	 * @param extent
	 * @param newfile
	 */
	public static void img2file(BufferedImage img, String extent, String newfile) {
		try {
			ImageIO.write(img, extent, new File(newfile));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 造定长定宽的定色图片，前期测试用
	 *
	 * @param width
	 * @param height
	 * @throws IOException
	 */
	public void createImage(int width, int height) throws IOException {
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D graphic = bi.createGraphics();
		graphic.setColor(new Color(0.2f, 0.3f, 0.4f, 0.4f));
		graphic.fillRect(0, 0, width, height);

		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				// result[i][j] = bi.getRGB(i, j) & 0xFFFFFF;
				System.out.println(bi.getRGB(i, j));
				// bi.setRGB(i, j, 0xFFFFFF);
			}
		}

		Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("png");
		ImageWriter writer = it.next();
		File f = new File("c://test02.png");
		ImageOutputStream ios = ImageIO.createImageOutputStream(f);
		writer.setOutput(ios);

		writer.write(bi);
	}


	// 图片转黑白
	@SuppressWarnings("restriction")
	public static void changeImge(File img) {
		try {
			Image image = ImageIO.read(img);
			int srcH = image.getHeight(null);
			int srcW = image.getWidth(null);
			BufferedImage bufferedImage = new BufferedImage(srcW, srcH, BufferedImage.TYPE_3BYTE_BGR);
			bufferedImage.getGraphics().drawImage(image, 0, 0, srcW, srcH, null);
			bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null).filter(bufferedImage,
					null);
			FileOutputStream fos = new FileOutputStream(img);

			ImageIO.write(bufferedImage, "jpeg", fos);

//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
//			encoder.encode(bufferedImage);

			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalStateException("图片转换出错！", e);
		}
	}
	// 图片转黑白
	@SuppressWarnings("restriction")
	public static BufferedImage  changeImge(BufferedImage bufferedImg) {
		Image image = bufferedImg;
		int srcH = image.getHeight(null);
		int srcW = image.getWidth(null);
		BufferedImage bufferedImage = new BufferedImage(srcW, srcH, BufferedImage.TYPE_3BYTE_BGR);
		bufferedImage.getGraphics().drawImage(image, 0, 0, srcW, srcH, null);
		bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null).filter(bufferedImage,
				null);

		return bufferedImage;
	}

	/**
	 * 图片颜色的处理
	 * @param alpha //透明名度
	 * 三原色
	 * @param red
	 * @param green
	 * @param blue
	 * @return
	 */
	private static int colorToRGB(int alpha, int red, int green, int blue) {

		/************************************************************
		 * 对于正数和负数在不考虑溢出的情况下，他们的运算如下：           *
		 * 3 << 2，则是将数字3左移2位，解释如下：                      *
		 * 左移一位都相当于乘以2的1次方，左移n位就相当于乘以2的n次方。 *
		 * 即  newPixel << 8  即等于 newPixel * 2^8                     *
		 * **********************************************************
		 */
		int newPixel = 0;
		newPixel += alpha;
		newPixel = newPixel << 8;
		newPixel += red;
		newPixel = newPixel << 8;
		newPixel += green;
		newPixel = newPixel << 8;
		newPixel += blue;

		return newPixel;

	}
	public static BufferedImage img2gray(BufferedImage bufferedImage) throws IOException {

		//获取到图片的属性信息
		BufferedImage grayImage =
				new BufferedImage(bufferedImage.getWidth(),
						bufferedImage.getHeight(),
						bufferedImage.getType());
		//图片的宽高
		System.out.println("getWidth----->"+bufferedImage.getWidth());

		for (int i = 0; i < bufferedImage.getWidth(); i++) {
			for (int j = 0; j < bufferedImage.getHeight(); j++) {
				/**------------------------------------------------------
				 * 得到 i,j 每个坐标像素在RGB颜色模板和默认的sRGB的色彩空间 |
				 * color一个整数像素在默认的RGB颜色模型和默认的sRGB色彩 |
				 **------------------------------------------------------
				 */
				final int color = bufferedImage.getRGB(i, j);
				/**----------------------------------------------------------
				 * 像素的右移  得到 三原色                                            |
				 * 颜色RGB颜色是由红(Red)、绿(Green)、蓝(Blue)三原色组成的，  |
				 * 所以可以使用这三个颜色的组合来代表一种具体的颜色，其中R、    |
				 * G、B的每个数值都位于0-255之间。在表达颜色的时候，         |
				 * 即可以使用三个数字来表达，也可以使用一个格式如0X00RRGGBB    |
				 * 这样格式的十六进制来表达，下面是常见颜色的表达形式：           |
				 *  red = (rgb & 0x00ff0000) >> 16                                                      |
				 　　               *  红色：(255,0,0)或0x00FF0000                             |
				 *  green = (color & 0x0000ff00) >> 8                                                       |
				 　　               *  绿色：(0,255,0)或0x0000FF00                             |
				 　　               *  blue = (color & 0x000000ff)                                                     |
				 　　               *  蓝色：(255,255,255)或0x00FFFFFF                             |
				 *-----------------------------------------------------------
				 */
				final int r = (color >> 16) & 0xff;     //右移四位
				final int g = (color >> 8) & 0xff;      //右移3为
				final int b = color & 0xff;
				//运用灰度处理 的方法  加权平均值
				int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);
				//每一个像素点的灰度转化
				int newPixel = colorToRGB(255, gray, gray, gray);
				grayImage.setRGB(i, j, newPixel);
			}
		}
		return grayImage;
	}
}
