Java图像处理工具类


本工具类的功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等

复制代码 代码如下:

package net.kitbox.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImagingOpException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
 * author:lldy
 * time:2012-5-6下午6:37:18
 * 图片处理工具类:<br>
 * 功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等
 */
public class ImageUtils {
    /**
     * 相对于图片的位置
     */
    private static final int POSITION_UPPERLEFT=0;
    private static final int POSITION_UPPERRIGHT=10;
    private static final int POSITION_LOWERLEFT=1;
    private static final int POSITION_LOWERRIGHT=11;
    /**
     * 几种常见的图片格式
     */
    public static String IMAGE_TYPE_GIF = "gif";// 图形交换格式
    public static String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
    public static String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
    public static String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式
    public static String IMAGE_TYPE_PNG = "png";// 可移植网络图形
    private static ImageUtils instance;
    private ImageUtils() {
        instance = this;
    }
    /**
     * 获取实例
     * @return
     */
    public static ImageUtils getInstance() {
        if (instance == null) {
            instance = new ImageUtils();
        }
        return instance;
    }
    public  BufferedImage image2BufferedImage(Image image){
        System.out.println(image.getWidth(null));
        System.out.println(image.getHeight(null));
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, null, null);
        g.dispose();
        System.out.println(bufferedImage.getWidth());
        System.out.println(bufferedImage.getHeight());
        return bufferedImage;
    }
    /**
     * 缩放并转换格式后保存
     * @param srcPath源路径
     * @param destPath目标路径
     * @param width:目标宽
     * @param height:目标高
     * @param format:文件格式
     * @return
     */
    public static boolean scaleToFile(String srcPath, String destPath, int width,  int height,String format) {
        boolean flag = false;
        try {
            File file = new File(srcPath);
            File destFile = new File(destPath);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdir();
            }
            BufferedImage src = ImageIO.read(file); // 读入文件
            Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            flag = ImageIO.write(tag, format, new FileOutputStream(destFile));// 输出到文件流
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * 缩放Image,此方法返回源图像按百分比缩放后的图像
     * @param inputImage
     * @param percentage 百分比 允许的输入0<percentage<10000
     * @return
     */
    public static BufferedImage scaleByPercentage(BufferedImage inputImage,int percentage){
        //允许百分比
        if(0>percentage||percentage>10000){
            throw new ImagingOpException("Error::不合法的参数:percentage->"+percentage+",percentage应该大于0~小于10000");
        }      
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        //获取目标图像大小
        int w=inputImage.getWidth()*percentage;
        int h=inputImage.getHeight()*percentage;
        //开启抗锯齿
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
        BufferedImage img = new BufferedImage(w, h, type);
        Graphics2D graphics2d =img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);       
        graphics2d.drawImage(inputImage, 0, 0, w, h, 0, 0, inputImage
                .getWidth(), inputImage.getHeight(), null);
        graphics2d.dispose();
        return img;
        /*此代码将返回Image类型
        return inputImage.getScaledInstance(inputImage.getWidth()*percentage,
                inputImage.getHeight()*percentage, Image.SCALE_SMOOTH);
        */
    }
    /**
     * 缩放Image,此方法返回源图像按给定最大宽度限制下按比例缩放后的图像
     * @param inputImage
     * @param maxWidth:压缩后允许的最大宽度
     * @param maxHeight:压缩后允许的最大高度
     * @throws java.io.IOException
     * return
     */
    public static BufferedImage scaleByPixelRate(BufferedImage inputImage, int maxWidth, int maxHeight) throws Exception {
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int width = inputImage.getWidth();
        int height = inputImage.getHeight();
        int newWidth = maxWidth;
        int newHeight =maxHeight;
        //如果指定最大宽度超过比例
        if(width*maxHeight<height*maxWidth){
            newWidth=(int)(newHeight*width/height) ;
        }
        //如果指定最大高度超过比例
        if(width*maxHeight>height*maxWidth){
            newHeight=(int)(newWidth*height/width);
        }
        //开启抗锯齿
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
        BufferedImage img = new BufferedImage(newWidth, newHeight, type);
        Graphics2D graphics2d =img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);       
        graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
        graphics2d.dispose();
        return img;
    }
    /**
     * 缩放Image,此方法返回源图像按给定宽度、高度限制下缩放后的图像
     * @param inputImage
     * @param maxWidth:压缩后宽度
     * @param maxHeight:压缩后高度
     * @throws java.io.IOException
     * return
     */
    public static BufferedImage scaleByPixel(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int width = inputImage.getWidth();
        int height = inputImage.getHeight();
        //开启抗锯齿
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        BufferedImage img = new BufferedImage(newWidth, newHeight, type);
        Graphics2D graphics2d =img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);       
        graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
        graphics2d.dispose();
        return img;
    }
    /**
     * 切割图像,返回指定范围的图像
     * @param inputImage
     * @param x 起点横坐标
     * @param y 起点纵坐标
     * @param width 切割图片宽度:如果宽度超出图片,将改为图片自x剩余宽度
     * @param height 切割图片高度:如果高度超出图片,将改为图片自y剩余高度
     * @param fill 指定目标图像大小超出时是否补白,如果true,则表示补白;false表示不补白,此时将重置目标图像大小
     * @return
     */
    public static BufferedImage cut(BufferedImage inputImage,int x,int y,int width,int height,boolean fill){
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int w = inputImage.getWidth();
        int h = inputImage.getHeight();
        int endx=x+width;
        int endy=y+height;
        if(x>w)
            throw new ImagingOpException("起点横坐标超出源图像范围");
        if(y>h)
            throw new ImagingOpException("起点纵坐标超出源图像范围");
        BufferedImage img;
        //补白
        if(fill){
            img = new BufferedImage(width, height, type);
            //宽度超出限制
            if((w-x)<width){
                width=w-x;
                endx=w;
            }
            //高度超出限制
            if((h-y)<height){
                height=h-y;
                endy=h;
            }
        //不补
        }else{
            //宽度超出限制
            if((w-x)<width){
                width=w-x;
                endx=w;
            }
            //高度超出限制
            if((h-y)<height){
                height=h-y;
                endy=h;
            }
            img = new BufferedImage(width, height, type); 
        }
        //开启抗锯齿
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
        Graphics2D graphics2d =img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);       
        graphics2d.drawImage(inputImage, 0, 0, width, height, x, y, endx, endy, null);
        graphics2d.dispose();
        return img;
    }
    /**
     * 切割图像,返回指定起点位置指定大小图像
     * @param inputImage
     * @param startPoint 起点位置:左上:0、右上:10、左下:1、右下:11
     * @param width 切割图片宽度
     * @param height 切割图片高度
     * @param fill 指定目标图像大小超出时是否补白,如果true,则表示补白;false表示不补白,此时将重置目标图像大小
     * @return
     */
    public static BufferedImage cut(BufferedImage inputImage,int startPoint,int width,int height,boolean fill){
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int w = inputImage.getWidth();
        int h = inputImage.getHeight();
        BufferedImage img;
        //补白
        if(fill){
            img = new BufferedImage(width, height, type);
            if(width>w)
                width=w;
            if(height>h)
                height=h;
        //不补
        }else{
            if(width>w)
                width=w;
            if(height>h)
                height=h;
            img = new BufferedImage(width, height, type);
        }
        //开启抗锯齿
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_ANTIALIAS_ON);
        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);      
        Graphics2D graphics2d =img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);
        switch(startPoint){
                //右上
            case POSITION_UPPERRIGHT:
                graphics2d.drawImage(inputImage, w-width, 0, w, height, 0, 0, width, height, null);
                break;
                //左下
            case POSITION_LOWERLEFT:
                graphics2d.drawImage(inputImage, 0, h-height, width, h, 0, 0, width, height, null);  
                break;
                //右下
            case POSITION_LOWERRIGHT:
                graphics2d.drawImage(inputImage, w-width, h-height, w, h, 0, 0, width, height, null);
                break;
                //默认左上
            case POSITION_UPPERLEFT:
            default:
                graphics2d.drawImage(inputImage, 0, 0, width, height, 0, 0, width, height, null);
        }
        graphics2d.dispose();
        return img;
    }
    /**
     * 以指定角度旋转图片:使用正角度 theta 进行旋转,可将正 x 轴上的点转向正 y 轴。
 &nbs