package com.mortals.xhx.base.login.service;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * gif动态图验证码图片生成器
 *
 */
public class GifSecurityImage {
	
    private static Log logger = LogFactory.getLog(GifSecurityImage.class);

	public static BufferedImage createImage(String securityCode) {
		int codeLength = securityCode.length();

		int fSize = 14;
		int fWidth = fSize + 1;

		int width = codeLength * fWidth + 6;

		int height = fSize * 2 + 1;
		BufferedImage image = new BufferedImage(width, height, 1);
		Graphics g = image.createGraphics();

		g.setColor(Color.WHITE);

		g.fillRect(0, 0, width, height);

		g.setColor(Color.LIGHT_GRAY);

		g.setFont(new Font("Arial", 1, height - 2));

		Random rand = new Random();
		// 画点
		g.setColor(Color.LIGHT_GRAY);
		for (int i = 0; i < codeLength * 10; i++) {
			g.setColor(randomColor());
			int x = rand.nextInt(width);
			int y = rand.nextInt(height);
			g.drawOval(x, y, 1, 1);
		}

		for (int i = 0; i < 5; i++) {
			g.setColor(randomColor());
			int x = rand.nextInt(width - 1);
			int y = rand.nextInt(height - 1);
			int xl = rand.nextInt(6) + 1;
			int yl = rand.nextInt(12) + 1;
			g.drawLine(x, y, xl, yl);
		}

		// 写字
		g.setFont(new Font("Georgia", 1, fSize));
		for (int i = 0; i < codeLength; i++) {
			int codeY = height - 8 - rand.nextInt(5);
			int codeX = width / 4 * i + (width / 4 - fSize) / 2;
			g.drawString(String.valueOf(securityCode.charAt(i)), codeX, codeY);
		}
		g.dispose();

		return image;
	}
	
	public static byte[] createGifImage(String securityCode) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();
		gifEncoder.setRepeat(0);
		gifEncoder.start(outputStream);
		for (int j = 0; j < 4; j++) {
			gifEncoder.setDelay(200); // 设置播放的延迟时间
			gifEncoder.addFrame(createImage(securityCode));
		}
		gifEncoder.finish();
		return outputStream.toByteArray();
	}

	private static Color randomColor() {
		Random random = new Random();
		int r = random.nextInt(256);
		int g = random.nextInt(256);
		int b = random.nextInt(256);
		return new Color(r, g, b);
	}

	public static ByteArrayInputStream getImageAsInputStream(String securityCode) {
		BufferedImage image = createImage(securityCode);
		return convertImageToStream(image);
	}

	private static ByteArrayInputStream convertImageToStream(BufferedImage image) {
		ByteArrayInputStream inputStream = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			byte[] bts = bos.toByteArray();
			inputStream = new ByteArrayInputStream(bts);
			ImageIO.write(image, "JPG", bos);
		} catch (Exception e) {
		    logger.debug("转换图片数据流异常-->" + e.getMessage());
		}
		return inputStream;
	}
	
}
