package com.house365.web.util;

import com.house365.beans.entity.BaseAttachment;
import com.house365.commons.system.FastDFSUtil;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.Iterator;

/**
 * Description
 *
 * @author Administrator
 * @date 2018/7/27
 */
public class PicCut {

    public static BaseAttachment  cut(int x, int y, int width, int height, String srcpath, BaseAttachment attachment) throws Exception {//裁剪方法
        BufferedInputStream is = null;
        ImageInputStream iis = null;
        try {
            //读取原始图片
            String format = srcpath.substring(srcpath.lastIndexOf(".")+1);
            String uploadFileName=srcpath.substring(srcpath.lastIndexOf("/")+1);
            URL url = new URL(srcpath);
            is = new BufferedInputStream(url.openStream());
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(format);
            ImageReader reader = it.next();
            //获取图片流
            iis = ImageIO.createImageInputStream(is);
            //将iis标记为true（只向前搜索）意味着包含在输入源中的图像将只按顺序读取
            reader.setInput(iis, true);
            //指定如何在输入时从 Java Image I/O框架的上下文中的流转换一幅图像或一组图像
            ImageReadParam param = reader.getDefaultReadParam();
            //定义空间中的一个区域
            Rectangle rect = new Rectangle(x, y, width, height);
            //提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion(rect);
            //读取索引imageIndex指定的对象
            BufferedImage bi = reader.read(0, param);
            //保存新图片
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bi, format, out);
            String path=FastDFSUtil.uploadFileByByteArray(out.toByteArray(),uploadFileName);
            attachment.setSize((long)out.size());
            attachment.setSuffix(format);
            attachment.setRemotePath(path);
            return attachment;
        } finally {
            if (is != null){
                is.close();
            }
            if (iis != null){
                iis.close();
            }

        }
    }
    public static void main(String[] args) throws Exception {
//        PicCut.cut(20, 20, 100, 100,"http://192.168.105.100/M00/00/24/wKhpZFtadnuIb-aoAAWnsPcGjNQAAAATwD91I8ABafI816.png");
//        System.out.println("ok");
    }
}
