Java++:图片裁剪处理(JDK方式)

工具类:

package com.yzh.util;

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

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MLQ
 * @Description: 图片截取
 * @date 2020年6月9日21:26:04
 */
public class ImageCut {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageCut.class);

    /**
     * 截取高度
     */
    private static final Integer FIXED_HEIGHT = 800;

    public static List<BufferedImage> cut(String srcPath) {

        List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>();
        InputStream inputStream = null;
        String postfix = getPostfix(srcPath);
        try {
            URL url = new URL(srcPath);
            inputStream = url.openConnection().getInputStream();
            BufferedImage image = ImageIO.read(inputStream);
            int height = image.getHeight();
            int width = image.getWidth();
            int x = 0;
            int y = 0;
            int cutOutHeight = (height <= FIXED_HEIGHT) ? height : FIXED_HEIGHT;
            int count = (height / FIXED_HEIGHT) == 0 ? 1 : height / FIXED_HEIGHT;
            for (int i = 1; i <= count; i++) {
                BufferedImage result = image.getSubimage(x, y, width, cutOutHeight);
                bufferedImages.add(result);
                y += FIXED_HEIGHT;
                cutOutHeight = FIXED_HEIGHT;
                if (height - (i * FIXED_HEIGHT) < FIXED_HEIGHT && height - (i * FIXED_HEIGHT) > 0) {
                    cutOutHeight = height - (i * FIXED_HEIGHT);
                    count++;
                }
            }
        } catch (Exception e) {
            LOGGER.error("图片截图异常:param={},error={}" + e.getMessage(), srcPath, e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bufferedImages;
    }

    /**
     * 获取文件后缀名
     *
     * @param inputFilePath 文件路径
     * @return
     */
    private static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    public static void main(String[] args) throws Exception {

        //cut("E:\\MaLQ-TestProject\\MaLQ-TestProject-Trunk\\MaLQ-TestProject\\libs\\see.png");

        cut("https://static.yzhlink.cn/1461032172755437949.jpg");

    }
}

写入到本地:

File path = new File("tmp");
if (!path.exists() || !path.isDirectory()) {
    path.mkdirs();
}
File file = new File(path, fileName);
ImageIO.write(bufferedImage, suffix, file);

 

posted @ 2021-05-31 14:00  coding++  阅读(360)  评论(0编辑  收藏  举报