package com.zf.image; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; public class ImageUtil { /** * 截取图片 * @param source 源图像 * @param output 目标图像的输出流 * @param a 相对于源图片的左上角的顶点 * @param b 相对于源图片的右上角的顶点 * @param c 相对于源图片的左下角的顶点 * @param d 相对于源图片的右下角的顶点 * @throws IOException */ public static void interception(InputStream source , OutputStream output , Point a , Point b , Point c , Point d) throws IOException{ int width = b.x - a.x ; int height = c.y - a.y ; BufferedImage sourceImage = ImageIO.read(source); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR) ; for (int i = 0; i < target.getWidth() ; i++) { for (int j = 0; j < target.getHeight() ; j++) { int sourceX = a.x + i ; int sourceY = a.y + j ; int rgb = sourceImage.getRGB(sourceX , sourceY) ; target.setRGB(i , j , rgb ); } } ImageIO.write(target, "jpg", output ) ; } /** * 缩放图片 * @param source 源图像 * @param output 目标图像的输出流 * @param targetWidth 目标图像的宽度 * @param targetHeight 目标图像的高度 * @throws IOException */ public static void zoom(InputStream source , OutputStream output , int targetWidth , int targetHeight) throws IOException{ Image sourceImage = ImageIO.read(source); BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_BGR); Graphics2D g2 = targetImage.createGraphics() ; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(sourceImage, 0, 0, targetWidth, targetHeight , null); g2.dispose(); ImageIO.write(targetImage, "JPEG", output); } }