package cn.com.qmth.stmms.common.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public final class ImageUtil {

    /**
     * 图片水印
     * 
     * @param pressImg
     *            水印图片
     * @param targetImg
     *            目标图片
     * @param x
     *            修正值 默认在中间
     * @param y
     *            修正值 默认在中间
     * @param alpha
     *            透明度
     */
    public final static void pressImage(String pressImg, String targetImg, int x, int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao,
                    null);
            // 水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文字水印
     * 
     * @param pressText
     *            水印文字
     * @param targetImg
     *            目标图片
     * @param fontName
     *            字体名称
     * @param fontStyle
     *            字体样式
     * @param color
     *            字体颜色
     * @param fontSize
     *            字体大小
     * @param x
     *            修正值
     * @param y
     *            修正值
     * @param alpha
     *            透明度
     */
    public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color,
            int fontSize, int x, int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 缩放
     * 
     * @param filePath
     *            图片路径
     * @param newFileName
     *            缩放完比图片路径
     * @param height
     *            高度
     * @param width
     *            宽度
     * @param bb
     *            比例不对时是否需要补白
     */
    @SuppressWarnings("static-access")
    public static void resize(String filePath, String newFileName, int height, int width, String formatName, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            File f = new File(filePath);
            BufferedImage bi = ImageIO.read(f);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue() / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                g.dispose();
                itemp = image;
            }
            BufferedImage outbi = null;
            if (itemp instanceof BufferedImage)
                outbi = (BufferedImage) itemp;
            else
                outbi = convertImageToBuffer(itemp);

            File newFile = null;
            if (newFileName == null || newFileName.length() == 0) {
                newFile = f;
            } else {
                newFile = new File(newFileName);
                if (!newFile.getParentFile().exists())
                    newFile.getParentFile().mkdirs();
            }
            ImageIO.write(outbi, formatName, newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对流缩放
     * 
     * @param input
     *            图片流
     * @param formatName
     *            图片格式
     * @param height
     *            高度
     * @param width
     *            宽度
     * @param bb
     *            比例不对时是否需要补白
     */
    @SuppressWarnings("static-access")
    public static InputStream MemoryResize(InputStream input, String formatName, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            BufferedImage bi = ImageIO.read(input);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue() / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                g.dispose();
                itemp = image;
            }
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            BufferedImage outbi = null;
            if (itemp instanceof BufferedImage)
                outbi = (BufferedImage) itemp;
            else
                outbi = convertImageToBuffer(itemp);

            ImageIO.write(outbi, formatName, output);
            byte[] buff = output.toByteArray();
            return new ByteArrayInputStream(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 裁剪图片
     * 
     * @param img
     * @param dest
     * @param top
     * @param left
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public static boolean cutImage(File img, String dest, int top, int left, int width, int height) throws IOException {
        File fileDest = new File(dest);
        if (!fileDest.getParentFile().exists())
            fileDest.getParentFile().mkdirs();
        String ext = getExtension(dest).toLowerCase();
        BufferedImage bi = (BufferedImage) ImageIO.read(img);
        height = Math.min(height, bi.getHeight());
        width = Math.min(width, bi.getWidth());
        if (height <= 0)
            height = bi.getHeight();
        if (width <= 0)
            width = bi.getWidth();
        top = Math.min(Math.max(0, top), bi.getHeight() - height);
        left = Math.min(Math.max(0, left), bi.getWidth() - width);

        BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);
        return ImageIO.write(bi_cropper, ext.equals("png") ? "png" : "jpg", fileDest);
    }

    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }

    public static String getExtension(File f) {
        return (f != null) ? getExtension(f.getName()) : "";
    }

    public static String getExtension(String filename) {
        return getExtension(filename, "");
    }

    public static String getExtension(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return defExt;
    }

    public static String trimExtension(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length()))) {
                return filename.substring(0, i);
            }
        }
        return filename;
    }

    /**
     * 转化Image 为 BufferedImage
     * 
     * @param img
     * @return
     */
    private static BufferedImage convertImageToBuffer(Image img) {
        BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return bufferedImage;
    }
}
