package com.apobates.forum.thumbnail.handler;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
 * 从中心点开始裁剪.不支持缩放
 * 
 * @author xiaofanku
 * @since 20191022
 */
public class FixedCenterCropHandler extends AbstractCropImageHandler{
	public FixedCenterCropHandler(File orginalImageFile) {
		super(orginalImageFile);
	}
	
	@Override
	public void cropImage(File cropSaveFile, int width, int height) throws IOException{
		BufferedImage originalImage = ImageIO.read(getOrginalImageFile());
		int[] xyPointers = getCropXYPointer(originalImage.getWidth(), originalImage.getHeight(), width, height);
		if(xyPointers.length == 0){
			return;
		}
		BufferedImage croppedImage = originalImage.getSubimage(xyPointers[0], xyPointers[1], width, height);
		String fileExt = getFileExtension(getFileName(cropSaveFile));
		ImageIO.write(croppedImage, fileExt, cropSaveFile);
	}
	
	/**
	 * 获取裁剪的起始点坐标
	 * 
	 * @param originalImageWidth  原始图片的宽度
	 * @param originalImageHeight 原始图片的高度
	 * @param width               裁剪的宽度
	 * @param height              裁剪的高度
	 * @return
	 */
	private int[] getCropXYPointer(int originalImageWidth, int originalImageHeight, int width, int height){
		if(originalImageWidth <= width && originalImageHeight <= height){
			return new int[]{};
		}
		
		int startX=0;
		if(originalImageWidth > width){
			int centerX = originalImageWidth / 2; //宽度中心点X
			startX = centerX - width / 2;
		}
		int startY=0;
		if(originalImageHeight > height){
			int centerY = originalImageHeight / 2; //高度中心点Y
			startY = centerY - height / 2;
		}
		return new int[]{startX, startY};
	}
}
