Here you can find the source of crop(BufferedImage source, File to, int x1, int y1, int x2, int y2)
Parameter | Description |
---|---|
originalImage | The image file |
to | The destination file |
x1 | The new x origin |
y1 | The new y origin |
x2 | The new x end |
y2 | The new y end |
public static void crop(BufferedImage source, File to, int x1, int y1, int x2, int y2)
//package com.java2s; //License from project: Open Source License import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; public class Main { /**//from w ww. j a v a 2 s. c om * Crop an image * * @param originalImage * The image file * @param to * The destination file * @param x1 * The new x origin * @param y1 * The new y origin * @param x2 * The new x end * @param y2 * The new y end */ public static void crop(File originalImage, File to, int x1, int y1, int x2, int y2) { try { BufferedImage source = ImageIO.read(originalImage); crop(source, to, x1, y1, x2, y2); } catch (Exception e) { throw new RuntimeException(e); } } /** * Crop an image * * @param originalImage * The image file * @param to * The destination file * @param x1 * The new x origin * @param y1 * The new y origin * @param x2 * The new x end * @param y2 * The new y end */ public static void crop(BufferedImage source, File to, int x1, int y1, int x2, int y2) { try { String mimeType = "image/jpeg"; if (to.getName().endsWith(".png")) { mimeType = "image/png"; } if (to.getName().endsWith(".gif")) { mimeType = "image/gif"; } int width = x2 - x1; int height = y2 - y1; // out BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Image croppedImage = source.getSubimage(x1, y1, width, height); Graphics graphics = dest.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, width, height); graphics.drawImage(croppedImage, 0, 0, null); ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next(); writer.setOutput(new FileImageOutputStream(to)); IIOImage image = new IIOImage(dest, null, null); writer.write(null, image, createImageWriteParam(writer)); } catch (Exception e) { throw new RuntimeException(e); } } public static ImageWriteParam createImageWriteParam(ImageWriter writer) { ImageWriteParam params = writer.getDefaultWriteParam(); // JPEGImageWriteParam jpegImageWriteParam = new // JPEGImageWriteParam(writer.getLocale()); // jpegImageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // jpegImageWriteParam.setCompressionQuality(0.8F); params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); params.setCompressionQuality(0.95F); return params; } }