Java 簡單圖片截取

package cn.byref.demo.image;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
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;

import org.junit.Test;

public class ImageDemo {
    @Test
    public void test_cut_image() throws IOException {
        String imgPath = "C:\\Users\\GJ\\Desktop\\1.jpg";
        String subPath = "C:\\Users\\GJ\\Desktop\\2.jpg";

        File f = new File(imgPath);
        File t = new File(subPath);
        if (t.exists()) {
            t.delete();
        }
        
        //圖片輸入流
        ImageInputStream iis = ImageIO.createImageInputStream(f);
        
        //圖片讀取器
        Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
        
        if (it.hasNext()) {
            ImageReader r = it.next();
            
            //設置輸入流
            r.setInput(iis, true);
            System.out.println("格式=" + r.getFormatName());
            System.out.println("寬=" + r.getWidth(0));
            System.out.println("高=" + r.getHeight(0));
            
            //讀取參數
            ImageReadParam param = r.getDefaultReadParam();
            
            //建立要截取的矩形範圍
            Rectangle rect = new Rectangle(100, 100, 400, 200);
            
            //設置截取範圍參數
            param.setSourceRegion(rect);
            
            //讀取截圖數據
            BufferedImage bi = r.read(0, param);

            // 保存圖片
            ImageIO.write(bi, "jpg", t);
        }
    }
}
相關文章
相關標籤/搜索