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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南