Java examples for 2D Graphics:Image
cut Picture
//package com.java2s; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; public class Main { public static boolean cutPic(String srcFile, String outFile, int x, int y, int width, int height) { FileInputStream is = null; ImageInputStream iis = null; try {/*from w w w .j a va2 s.c om*/ // if (!new File(srcFile).exists()) { return false; } // is = new FileInputStream(srcFile); // ? String ext = srcFile.substring(srcFile.lastIndexOf(".") + 1); // ImageReader Iterator<ImageReader> it = ImageIO .getImageReadersByFormatName(ext); ImageReader reader = it.next(); // iis = ImageIO.createImageInputStream(is); // ? reader.setInput(iis, true); // ImageReadParam param = reader.getDefaultReadParam(); // ? Rectangle rect = new Rectangle(x, y, width, height); // BufferedImage param.setSourceRegion(rect); // ImageReadParam imageIndex ? BufferedImage bi = reader.read(0, param); // File tempOutFile = new File(outFile); if (!tempOutFile.exists()) { tempOutFile.mkdirs(); } ImageIO.write(bi, ext, new File(outFile)); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (is != null) { is.close(); } if (iis != null) { iis.close(); } } catch (IOException e) { e.printStackTrace(); return false; } } } }