All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.net.wanmo.common.image.ImageCutUtil Maven / Gradle / Ivy

The newest version!
package cn.net.wanmo.common.image;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 裁剪工具
 */
public class ImageCutUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageCutUtil.class);

    /**
     * 裁剪图片
     *
     * @param srcImageFile 需要裁剪的图片
     * @param x            裁剪时x的坐标(左上角)
     * @param y            裁剪时y的坐标(左上角)
     * @param width        裁剪后的图片宽度
     * @param height       裁剪后的图片高度
     * @return
     */
    public static File cut(File srcImageFile, int x, int y, int width, int height) {
        File targetFile = null;
        try {
            targetFile = File.createTempFile("image_cut_", "." + ImageUtil.getSuffix(srcImageFile));
            boolean flag = cut(srcImageFile, targetFile, x, y, width, height);

            if (flag == false && targetFile != null) {
                targetFile.deleteOnExit();
                targetFile = null;
            }
        } catch (IOException e) {
            logger.error("裁剪图片异常", e);
        }
        return targetFile;

    }


    /**
     * 裁剪图片
     *
     * @param srcImageFile  需要裁剪的图片
     * @param destImageFile 裁剪后的图片
     * @param x             裁剪时x的坐标(左上角)
     * @param y             裁剪时y的坐标(左上角)
     * @param width         裁剪后的图片宽度
     * @param height        裁剪后的图片高度
     * @return
     */
    public static boolean cut(File srcImageFile, File destImageFile, int x, int y, int width, int height) {
        boolean flag = false;
        try {
            //使用ImageIO的read方法读取图片
            BufferedImage read = ImageIO.read(srcImageFile);
            //调用裁剪方法
            BufferedImage image = read.getSubimage(x, y, width, height);

            //使用ImageIO的write方法进行输出
            ImageIO.write(image, ImageUtil.getFormatName(srcImageFile), destImageFile);
            flag = true;
        } catch (IOException e) {
            logger.error("裁剪图片异常", e);
        }
        return flag;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy