【知识积累】BufferedImage类实现图片的切分

一、引言

  如何实现图片分割?若有园友用到这个模块,使用Java的BufferedImage类来实现,图片切分也可以作为一个小工具积累起来,以备不时之需。

二、代码清单 

复制代码
package com.leesf.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

public class ImageUtil {
    // 切图
    public static ArrayList<BufferedImage> cutImage(String fileUrl, int rows,
            int cols, int nums) {
        ArrayList<BufferedImage> list = new ArrayList<BufferedImage>();
        try {
            BufferedImage img = ImageIO.read(new File(fileUrl));
            int lw = img.getWidth() / cols;
            int lh = img.getHeight() / rows;
            for (int i = 0; i < nums; i++) {
                BufferedImage buffImg = img.getSubimage(i % cols * lw, i / cols
                        * lh, lw, lh);
                list.add(buffImg);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) throws IOException {
        ArrayList<BufferedImage> biLists = ImageUtil.cutImage("img/image2.jpg",
                2, 2, 4);
        String fileNameString = "E:";
        int number = 0;
        String format = "jpg";
        for (BufferedImage bi : biLists) {
            File file1 = new File(fileNameString + File.separator + number
                    + "." + format);
            ImageIO.write(bi, format, file1);
            number++;
        }
    }
}
View Code
复制代码

  说明:可以切分任何图片,具体的参数园友可以自行配置~之后就可以在配置的目录下看到切分结果了。

三、总结

  要将平时遇到的一些小工具积累起来,以备不时之需。谢谢各位园友的观看~

posted @   leesf  阅读(1689)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示