Java crop / cut image - 使用Java 批量剪割图片

package cutpicture;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.*;import java.nio.file.*;import java.util.*;import java.util.stream.*;import javax.imageio.ImageIO;public class CutPicture {    public static void main(String[] args) throws IllegalAccessException, InstantiationException, IOException {        var dirName = "C:\\test\\";        var des = "C:\\destination\\";        for (var f : fileList(dirName)) {            File fullpath = new File(f.toString());                        String number = fullpath.getName().toString().split("_")[0];            cropImage(fullpath.toString(), number , des);            System.out.println(number);        }    }    public static List fileList(String dirName) {        List result = null;        try ( Stream<Path> walk = Files.walk(Paths.get(dirName))) {            result = walk.filter(p -> !Files.isDirectory(p)) // not a directory                    .map(p -> p.toString()) // convert path to string                    .filter(f -> f.endsWith("png")) // check end with                    .collect(Collectors.toList());        } catch (Exception e) {            e.printStackTrace();            System.out.println("List error ");            return null;        }        return result;    }    public static void cropImage(String filePath , String i , String des) {        try {            Image src = ImageIO.read(new File(filePath));            int x = 572, y = 28, w = 776, h = 1049;            BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);            dst.getGraphics().drawImage(src, 0, 0, w, h, x, y, x + w, y + h, null);            ImageIO.write(dst, "png", new File(des + i + "_cropped.jpg"));        } catch (Exception e) {            e.printStackTrace();            System.out.println("Crop Error");        }    }}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章