package utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;

public class ImageUtils {


    /**
     * 裁切图片
     *
     * @param imgFile
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static BufferedImage cutAreaImage(File imgFile, int x, int y, int width, int height) throws Exception {
        String resultFile = "cut/"+imgFile.getName().split("\\.")[0]+"_"+x+"_"+y+".jpg";
        BufferedImage image = ImageIO.read(imgFile);
        image = image.getSubimage(x, y, width, height);
        ImageIO.write(image, "jpg", new File(resultFile));
        return image;
    }


    /**
     * 缩放图片
     *
     * @param imgFile
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static File zoomImage(File imgFile, int width, int height) throws Exception{
        BufferedImage imageBuf = ImageIO.read(imgFile);
        BufferedImage zoomImg = new BufferedImage(width, height, imageBuf.getType());
        Image img = imageBuf.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        Graphics gc = zoomImg.getGraphics();
        gc.setColor(Color.WHITE);
        gc.drawImage(img, 0, 0, null);
        ImageIO.write(zoomImg, "jpg", imgFile);
        return imgFile;
    }


    /**
     * 获取图片的base64+UrlEncoder
     *
     * @param file
     * @return
     */
    public static String encodeImage(File file){
        String encodedFile = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(file);
            byte[] bytes = new byte[(int)file.length()];
            fileInputStreamReader.read(bytes);
            //转base64
            encodedFile = Base64.getEncoder().encodeToString(bytes);
            //url编码
            encodedFile = URLEncoder.encode(encodedFile, "UTF-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return encodedFile;
    }

}
