java实现图片裁切的工具类实例
程序员文章站
2024-03-06 17:00:32
本文实例讲述了java实现图片裁切的工具类。分享给大家供大家参考,具体如下:
package com.yanek.util;
import java.awt.r...
本文实例讲述了java实现图片裁切的工具类。分享给大家供大家参考,具体如下:
package com.yanek.util; import java.awt.rectangle; import java.awt.image.bufferedimage; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.util.iterator; import javax.imageio.imageio; import javax.imageio.imagereadparam; import javax.imageio.imagereader; import javax.imageio.stream.imageinputstream; public class imgcututil { /** * @param args */ public static void main(string[] args) { imgcututil.cut(30, 50, 300, 400, "d:/1.jpg", "d:/100.jpg"); } /** * 图片裁切 * @param x1 选择区域左上角的x坐标 * @param y1 选择区域左上角的y坐标 * @param width 选择区域的宽度 * @param height 选择区域的高度 * @param sourcepath 源图片路径 * @param descpath 裁切后图片的保存路径 */ public static void cut(int x1, int y1, int width, int height, string sourcepath, string descpath) { fileinputstream is = null; imageinputstream iis = null; try { is = new fileinputstream(sourcepath); string filesuffix = sourcepath.substring(sourcepath .lastindexof(".") + 1); iterator<imagereader> it = imageio .getimagereadersbyformatname(filesuffix); imagereader reader = it.next(); iis = imageio.createimageinputstream(is); reader.setinput(iis, true); imagereadparam param = reader.getdefaultreadparam(); rectangle rect = new rectangle(x1, y1, width, height); param.setsourceregion(rect); bufferedimage bi = reader.read(0, param); imageio.write(bi, filesuffix, new file(descpath)); } catch (exception ex) { ex.printstacktrace(); } finally { if (is != null) { try { is.close(); } catch (ioexception e) { e.printstacktrace(); } is = null; } if (iis != null) { try { iis.close(); } catch (ioexception e) { e.printstacktrace(); } iis = null; } } } }
希望本文所述对大家java程序设计有所帮助。
上一篇: aspx中页面按钮写返回上一页代码