简单的java图片处理类(图片水印 图片缩放)

2022-10-20,,,,

复制代码 代码如下:
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.toolkit;
import java.awt.color.colorspace;
import java.awt.geom.affinetransform;
import java.awt.image.affinetransformop;
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.io.file;
import java.io.ioexception;

import javax.imageio.imageio;

/**
 * 图片处理工具类:<br>
 * 功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印图片水印等
 * @author administrator
 */
public class imageutils {

    /**
     * 几种常见的图片格式
     */
    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";// 可移植网络图形
    public static string image_type_psd = "psd";// photoshop的专用格式photoshop

    /**
     * 程序入口:用于测试
     * @param args
     */
    public static void main(string[] args) {
        // 1-缩放图像:
        // 方法一:按比例缩放
        imageutils.scale("e:/abc.jpg", "e:/abc_scale.jpg", 2, true);//测试ok
        // 方法二:按高度和宽度缩放
        imageutils.scale2("e:/abc.jpg", "e:/abc_scale2.jpg", 500, 300, true);//测试ok

        // 2-切割图像:
        // 方法一:按指定起点坐标和宽高切割
        imageutils.cut("e:/abc.jpg", "e:/abc_cut.jpg", 0, 0, 400, 400 );//测试ok
        // 方法二:指定切片的行数和列数
        imageutils.cut2("e:/abc.jpg", "e:/", 2, 2 );//测试ok
        // 方法三:指定切片的宽度和高度
        imageutils.cut3("e:/abc.jpg", "e:/", 300, 300 );//测试ok

        // 3-图像类型转换:
        imageutils.convert("e:/abc.jpg", "gif", "e:/abc_convert.gif");//测试ok

        // 4-彩色转黑白:
        imageutils.gray("e:/abc.jpg", "e:/abc_gray.jpg");//测试ok

        // 5-给图片添加文字水印:
        // 方法一:
        imageutils.presstext("我是水印文字","e:/abc.jpg","e:/abc_presstext.jpg","宋体",font.bold,color.white,80, 0, 0, 0.5f);//测试ok
        // 方法二:
        imageutils.presstext2("我也是水印文字", "e:/abc.jpg","e:/abc_presstext2.jpg", "黑体", 36, color.white, 80, 0, 0, 0.5f);//测试ok

        // 6-给图片添加图片水印:
        imageutils.pressimage("e:/abc2.jpg", "e:/abc.jpg","e:/abc_pressimage.jpg", 0, 0, 0.5f);//测试ok
    }

    /**
     * 缩放图像(按比例缩放)
     * @param srcimagefile 源图像文件地址
     * @param result 缩放后的图像地址
     * @param scale 缩放比例
     * @param flag 缩放选择:true 放大; false 缩小;
     */
    public final static void scale(string srcimagefile, string result,
            int scale, boolean flag) {
        try {
            bufferedimage src = imageio.read(new file(srcimagefile)); // 读入文件
            int width = src.getwidth(); // 得到源图宽
            int height = src.getheight(); // 得到源图长
            if (flag) {// 放大
                width = width * scale;
                height = height * scale;
            } else {// 缩小
                width = width / scale;
                height = height / scale;
            }
            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();
            imageio.write(tag, "jpeg", new file(result));// 输出到文件流
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    /**
     * 缩放图像(按高度和宽度缩放)
     * @param srcimagefile 源图像文件地址
     * @param result 缩放后的图像地址
     * @param height 缩放后的高度
     * @param width 缩放后的宽度
     * @param bb 比例不对时是否需要补白:true为补白; false为不补白;
     */
    public final static void scale2(string srcimagefile, string result, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            file f = new file(srcimagefile);
            bufferedimage bi = imageio.read(f);
            image itemp = bi.getscaledinstance(width, height, bi.scale_smooth);
            // 计算比例
            if ((bi.getheight() > height) || (bi.getwidth() > width)) {
                if (bi.getheight() > bi.getwidth()) {
                    ratio = (new integer(height)).doublevalue()
                            / bi.getheight();
                } else {
                    ratio = (new integer(width)).doublevalue() / bi.getwidth();
                }
                affinetransformop op = new affinetransformop(affinetransform
                        .getscaleinstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {//补白
                bufferedimage image = new bufferedimage(width, height,
                        bufferedimage.type_int_rgb);
                graphics2d g = image.creategraphics();
                g.setcolor(color.white);
                g.fillrect(0, 0, width, height);
                if (width == itemp.getwidth(null))
                    g.drawimage(itemp, 0, (height - itemp.getheight(null)) / 2,
                            itemp.getwidth(null), itemp.getheight(null),
                            color.white, null);
                else
                    g.drawimage(itemp, (width - itemp.getwidth(null)) / 2, 0,
                            itemp.getwidth(null), itemp.getheight(null),
                            color.white, null);
                g.dispose();
                itemp = image;
            }
            imageio.write((bufferedimage) itemp, "jpeg", new file(result));
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    /**
     * 图像切割(按指定起点坐标和宽高切割)
     * @param srcimagefile 源图像地址
     * @param result 切片后的图像地址
     * @param x 目标切片起点坐标x
     * @param y 目标切片起点坐标y
     * @param width 目标切片宽度
     * @param height 目标切片高度
     */
    public final static void cut(string srcimagefile, string result,
            int x, int y, int width, int height) {
        try {
            // 读取源图像
            bufferedimage bi = imageio.read(new file(srcimagefile));
            int srcwidth = bi.getheight(); // 源图宽度
            int srcheight = bi.getwidth(); // 源图高度
            if (srcwidth > 0 && srcheight > 0) {
                image image = bi.getscaledinstance(srcwidth, srcheight,
                        image.scale_default);
                // 四个参数分别为图像起点坐标和宽高
                // 即: cropimagefilter(int x,int y,int width,int height)
                imagefilter cropfilter = new cropimagefilter(x, y, width, height);
                image img = toolkit.getdefaulttoolkit().createimage(
                        new filteredimagesource(image.getsource(),
                                cropfilter));
                bufferedimage tag = new bufferedimage(width, height, bufferedimage.type_int_rgb);
                graphics g = tag.getgraphics();
                g.drawimage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                imageio.write(tag, "jpeg", new file(result));
            }
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 图像切割(指定切片的行数和列数)
     * @param srcimagefile 源图像地址
     * @param descdir 切片目标文件夹
     * @param rows 目标切片行数。默认2,必须是范围 [1, 20] 之内
     * @param cols 目标切片列数。默认2,必须是范围 [1, 20] 之内
     */
    public final static void cut2(string srcimagefile, string descdir,
            int rows, int cols) {
        try {
            if(rows<=0||rows>20) rows = 2; // 切片行数
            if(cols<=0||cols>20) cols = 2; // 切片列数
            // 读取源图像
            bufferedimage bi = imageio.read(new file(srcimagefile));
            int srcwidth = bi.getheight(); // 源图宽度
            int srcheight = bi.getwidth(); // 源图高度
            if (srcwidth > 0 && srcheight > 0) {
                image img;
                imagefilter cropfilter;
                image image = bi.getscaledinstance(srcwidth, srcheight, image.scale_default);
                int destwidth = srcwidth; // 每张切片的宽度
                int destheight = srcheight; // 每张切片的高度
                // 计算切片的宽度和高度
                if (srcwidth % cols == 0) {
                    destwidth = srcwidth / cols;
                } else {
                    destwidth = (int) math.floor(srcwidth / cols) + 1;
                }
                if (srcheight % rows == 0) {
                    destheight = srcheight / rows;
                } else {
                    destheight = (int) math.floor(srcwidth / rows) + 1;
                }
                // 循环建立切片
                // 改进的想法:是否可用多线程加快切割速度
                for (int i = 0; i < rows; i++) {
                    for (int j = 0; j < cols; j++) {
                        // 四个参数分别为图像起点坐标和宽高
                        // 即: cropimagefilter(int x,int y,int width,int height)
                        cropfilter = new cropimagefilter(j * destwidth, i * destheight,
                                destwidth, destheight);
                        img = toolkit.getdefaulttoolkit().createimage(
                                new filteredimagesource(image.getsource(),
                                        cropfilter));
                        bufferedimage tag = new bufferedimage(destwidth,
                                destheight, bufferedimage.type_int_rgb);
                        graphics g = tag.getgraphics();
                        g.drawimage(img, 0, 0, null); // 绘制缩小后的图
                        g.dispose();
                        // 输出为文件
                        imageio.write(tag, "jpeg", new file(descdir
                                + "_r" + i + "_c" + j + ".jpg"));
                    }
                }
            }
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 图像切割(指定切片的宽度和高度)
     * @param srcimagefile 源图像地址
     * @param descdir 切片目标文件夹
     * @param destwidth 目标切片宽度。默认200
     * @param destheight 目标切片高度。默认150
     */
    public final static void cut3(string srcimagefile, string descdir,
            int destwidth, int destheight) {
        try {
            if(destwidth<=0) destwidth = 200; // 切片宽度
            if(destheight<=0) destheight = 150; // 切片高度
            // 读取源图像
            bufferedimage bi = imageio.read(new file(srcimagefile));
            int srcwidth = bi.getheight(); // 源图宽度
            int srcheight = bi.getwidth(); // 源图高度
            if (srcwidth > destwidth && srcheight > destheight) {
                image img;
                imagefilter cropfilter;
                image image = bi.getscaledinstance(srcwidth, srcheight, image.scale_default);
                int cols = 0; // 切片横向数量
                int rows = 0; // 切片纵向数量
                // 计算切片的横向和纵向数量
                if (srcwidth % destwidth == 0) {
                    cols = srcwidth / destwidth;
                } else {
                    cols = (int) math.floor(srcwidth / destwidth) + 1;
                }
                if (srcheight % destheight == 0) {
                    rows = srcheight / destheight;
                } else {
                    rows = (int) math.floor(srcheight / destheight) + 1;
                }
                // 循环建立切片
                // 改进的想法:是否可用多线程加快切割速度
                for (int i = 0; i < rows; i++) {
                    for (int j = 0; j < cols; j++) {
                        // 四个参数分别为图像起点坐标和宽高
                        // 即: cropimagefilter(int x,int y,int width,int height)
                        cropfilter = new cropimagefilter(j * destwidth, i * destheight,
                                destwidth, destheight);
                        img = toolkit.getdefaulttoolkit().createimage(
                                new filteredimagesource(image.getsource(),
                                        cropfilter));
                        bufferedimage tag = new bufferedimage(destwidth,
                                destheight, bufferedimage.type_int_rgb);
                        graphics g = tag.getgraphics();
                        g.drawimage(img, 0, 0, null); // 绘制缩小后的图
                        g.dispose();
                        // 输出为文件
                        imageio.write(tag, "jpeg", new file(descdir
                                + "_r" + i + "_c" + j + ".jpg"));
                    }
                }
            }
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 图像类型转换:gif->jpg、gif->png、png->jpg、png->gif(x)、bmp->png
     * @param srcimagefile 源图像地址
     * @param formatname 包含格式非正式名称的 string:如jpg、jpeg、gif等
     * @param destimagefile 目标图像地址
     */
    public final static void convert(string srcimagefile, string formatname, string destimagefile) {
        try {
            file f = new file(srcimagefile);
            f.canread();
            f.canwrite();
            bufferedimage src = imageio.read(f);
            imageio.write(src, formatname, new file(destimagefile));
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 彩色转为黑白
     * @param srcimagefile 源图像地址
     * @param destimagefile 目标图像地址
     */
    public final static void gray(string srcimagefile, string destimagefile) {
        try {
            bufferedimage src = imageio.read(new file(srcimagefile));
            colorspace cs = colorspace.getinstance(colorspace.cs_gray);
            colorconvertop op = new colorconvertop(cs, null);
            src = op.filter(src, null);
            imageio.write(src, "jpeg", new file(destimagefile));
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    /**
     * 给图片添加文字水印
     * @param presstext 水印文字
     * @param srcimagefile 源图像地址
     * @param destimagefile 目标图像地址
     * @param fontname 水印的字体名称
     * @param fontstyle 水印的字体样式
     * @param color 水印的字体颜色
     * @param fontsize 水印的字体大小
     * @param x 修正值
     * @param y 修正值
     * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
     */
    public final static void presstext(string presstext,
            string srcimagefile, string destimagefile, string fontname,
            int fontstyle, color color, int fontsize,int x,
            int y, float alpha) {
        try {
            file img = new file(srcimagefile);
            image src = imageio.read(img);
            int width = src.getwidth(null);
            int height = src.getheight(null);
            bufferedimage image = new bufferedimage(width, height,
                    bufferedimage.type_int_rgb);
            graphics2d g = image.creategraphics();
            g.drawimage(src, 0, 0, width, height, null);
            g.setcolor(color);
            g.setfont(new font(fontname, fontstyle, fontsize));
            g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawstring(presstext, (width - (getlength(presstext) * fontsize))
                    / 2 + x, (height - fontsize) / 2 + y);
            g.dispose();
            imageio.write((bufferedimage) image, "jpeg", new file(destimagefile));// 输出到文件流
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 给图片添加文字水印
     * @param presstext 水印文字
     * @param srcimagefile 源图像地址
     * @param destimagefile 目标图像地址
     * @param fontname 字体名称
     * @param fontstyle 字体样式
     * @param color 字体颜色
     * @param fontsize 字体大小
     * @param x 修正值
     * @param y 修正值
     * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
     */
    public final static void presstext2(string presstext, string srcimagefile,string destimagefile,
            string fontname, int fontstyle, color color, int fontsize, int x,
            int y, float alpha) {
        try {
            file img = new file(srcimagefile);
            image src = imageio.read(img);
            int width = src.getwidth(null);
            int height = src.getheight(null);
            bufferedimage image = new bufferedimage(width, height,
                    bufferedimage.type_int_rgb);
            graphics2d g = image.creategraphics();
            g.drawimage(src, 0, 0, width, height, null);
            g.setcolor(color);
            g.setfont(new font(fontname, fontstyle, fontsize));
            g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawstring(presstext, (width - (getlength(presstext) * fontsize))
                    / 2 + x, (height - fontsize) / 2 + y);
            g.dispose();
            imageio.write((bufferedimage) image, "jpeg", new file(destimagefile));
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 给图片添加图片水印
     * @param pressimg 水印图片
     * @param srcimagefile 源图像地址
     * @param destimagefile 目标图像地址
     * @param x 修正值。 默认在中间
     * @param y 修正值。 默认在中间
     * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
     */
    public final static void pressimage(string pressimg, string srcimagefile,string destimagefile,
            int x, int y, float alpha) {
        try {
            file img = new file(srcimagefile);
            image src = imageio.read(img);
            int wideth = src.getwidth(null);
            int height = src.getheight(null);
            bufferedimage image = new bufferedimage(wideth, height,
                    bufferedimage.type_int_rgb);
            graphics2d g = image.creategraphics();
            g.drawimage(src, 0, 0, wideth, height, null);
            // 水印文件
            image src_biao = imageio.read(new file(pressimg));
            int wideth_biao = src_biao.getwidth(null);
            int height_biao = src_biao.getheight(null);
            g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop,
                    alpha));
            g.drawimage(src_biao, (wideth - wideth_biao) / 2,
                    (height - height_biao) / 2, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            imageio.write((bufferedimage) image,  "jpeg", new file(destimagefile));
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    /**
     * 计算text的长度(一个中文算两个字符)
     * @param text
     * @return
     */
    public final static int getlength(string text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new string(text.charat(i) + "").getbytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }
}
 

《简单的java图片处理类(图片水印 图片缩放).doc》

下载本文的Word格式文档,以方便收藏与打印。