Java截取图片的一部分并保存为40*40的图片

时间:2021-11-17 08:59:29
@Test
    public void testImag() {
        try {
            String path = "E:/flower2.jpg";
            int x = 11, y = 20, cutW = 280, cutH = 280;
            BufferedImage image = ImageIO.read(new File(path));
            // 截取图片
            Rectangle rect = new Rectangle(x, y, cutW, cutH);
            BufferedImage areaImage = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
            // 新建一个40*40的Image
            BufferedImage buffImg = new BufferedImage(40, 40, BufferedImage.TYPE_INT_RGB);
            buffImg.getGraphics().drawImage(areaImage.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH), 0, 0, null);

            ImageIO.write(buffImg, "png", new File("E:/subImage1.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }