Java image cropping Tool

Source: Internet
Author: User

[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 */publ Ic static void main (String [] args) {ImgCutUtil. cut (30, 50,300,400, "d:/1.jpg"," d:/100.jpg ");} /*** image cropping ** @ param x1 select the x coordinate in the upper left corner of the area * @ param y1 select the y coordinate in the upper left corner of the area * @ param width select the area width * @ param height select the area * @ param sourcePath source image path * @ param descpath: Save the cropped image path */public static void cut (int x1, int y1, int width, int height, String sourcePath, String descpath) {FileInputStream is = null; ImageInput Stream 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 Rectangl E (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 ;}www.2cto.com if (iis! = Null) {try {iis. close () ;}catch (IOException e) {e. printStackTrace () ;}iis = null ;}}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.