Home > Java > javaTutorial > Introduction to image cropping function methods implemented in Java

Introduction to image cropping function methods implemented in Java

黄舟
Release: 2017-10-14 09:41:32
Original
1370 people have browsed it

这篇文章主要介绍了java实现的图片裁剪功能,涉及java针对图片的读取、转换、保存等相关操作技巧,需要的朋友可以参考下

本文实例讲述了java实现的图片裁剪功能。分享给大家供大家参考,具体如下:

PicCut.java:


package Tsets;
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 PicCut {
  public void cut(int x,int y,int width,int height,String srcpath,String subpath) throws IOException {//裁剪方法
    FileInputStream is = null;
    ImageInputStream iis = null;
    try {
      is = new FileInputStream(srcpath); //读取原始图片
      Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); //ImageReader声称能够解码指定格式
      ImageReader reader = it.next();
      iis = ImageIO.createImageInputStream(is); //获取图片流
      reader.setInput(iis, true); //将iis标记为true(只向前搜索)意味着包含在输入源中的图像将只按顺序读取
      ImageReadParam param = reader.getDefaultReadParam(); //指定如何在输入时从 Java Image I/O框架的上下文中的流转换一幅图像或一组图像
      Rectangle rect = new Rectangle(x, y, width, height); //定义空间中的一个区域
      param.setSourceRegion(rect); //提供一个 BufferedImage,将其用作解码像素数据的目标。
      BufferedImage bi = reader.read(0, param); //读取索引imageIndex指定的对象
      ImageIO.write(bi, "jpg", new File(subpath)); //保存新图片
    } finally {
      if (is != null)
        is.close();
      if (iis != null)
        iis.close();
    }
  }
  public static void main(String[] args) throws Exception {
      PicCut pc = new PicCut();
    pc.cut(20, 20, 100, 100,"D:\\1.jpg","D:\\11.jpg");
    System.out.println("ok");
  }
}
Copy after login

The above is the detailed content of Introduction to image cropping function methods implemented in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template