用到的jar包:

commons-beanutils-1.8.0.jar

commons-codec-1.10.jar

package com.zhenzhigu.commons.util;
 
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
 
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
 
/**
 * 图片工具类:
 * 功能:[裁剪/图片水印/文字水印/缩放补白/Base64加密解密]
 * @author Master.Xia date:2016年11月17日11:52:38
 */
public final class ImageUtils {
     
    /**图片格式:JPG*/
    private static final String PICTRUE_FORMATE_JPG = "jpg";
     
    private ImageUtils(){}
    /**
     * 图片裁剪
     * @param src        原始图片输入流
     * @param out        成品图片输出流
     * @param x          开始位置的x坐标
     * @param y          开始位置的y坐标
     * @param width      裁剪的宽度
     * @param height 裁剪的高度
     * @throws IOException
     */
    public static void cut(InputStream src, OutputStream out, int x, int y,int width, int height) throws IOException {
        Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) iterator.next();
        ImageInputStream iis = ImageIO.createImageInputStream(src);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(x, y, width, height);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, "jpg", out);
    }
    /**
     * 添加图片水印
     * @param src        原始图片输入流
     * @param out        成品图片输出流
     * @param water      水印图片输入流
     * @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 水印透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     */
    public final static void watermark(InputStream src,OutputStream out, InputStream water, int x, int y, float alpha) {
            try {
                Image image = ImageIO.read(src);
                int width = image.getWidth(null);
                int height = image.getHeight(null);
                BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bufferedImage.createGraphics();
                g.drawImage(image, 0, 0, width, height, null);
             
                Image waterImage = ImageIO.read(water);    // 水印文件
                int width_1 = waterImage.getWidth(null);
                int height_1 = waterImage.getHeight(null);
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
                 
                int widthDiff = width - width_1;
                int heightDiff = height - height_1;
                if(x < 0){
                    x = widthDiff / 2;
                }else if(x > widthDiff){
                    x = widthDiff;
                }
                if(y < 0){
                    y = heightDiff / 2;
                }else if(y > heightDiff){
                    y = heightDiff;
                }
                g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
                g.dispose();
                ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, out);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
 
    /**
     * 添加文字水印
     * @param src        原始图片输入流
     * @param out        成品图片输出流
     * @param waterText  水印文字, 如:夏老师V5
     * @param fontName   字体名称,    如:宋体|微软雅黑|楷体|...
     * @param fontStyle  字体样式:Font.BOLD|Font.ITALIC|...
     * @param fontSize   字体大小,单位为像素
     * @param color      字体颜色
     * @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 水印透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     */
    public static void watermark(InputStream src,OutputStream out, String waterText, String fontName, int fontStyle, int fontSize, Color color, int x, int y, float alpha) {
        try {
            Image image = ImageIO.read(src);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
             
            int width_1 = fontSize * getLength(waterText);
            int height_1 = fontSize;
            int widthDiff = width - width_1;
            int heightDiff = height - height_1;
            if(x < 0){
                x = widthDiff / 2;
            }else if(x > widthDiff){
                x = widthDiff;
            }
            if(y < 0){
                y = heightDiff / 2;
            }else if(y > heightDiff){
                y = heightDiff;
            }
             
            g.drawString(waterText, x, y + height_1);
            g.dispose();
            ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     
    /**
     * 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     * @param text
     * @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }
 
    /**
     * 图片缩放
     * @param src        原始图片输入流
     * @param out        成品图片输出流
     * @param height    缩放后的高度
     * @param width     缩放后的宽度
     * @param bb 比例不对时是否需要补白
     */
    public static void resize(InputStream src,OutputStream out, int height, int width, boolean bb) {
        try {
            double ratio = 0; //缩放比例     
            BufferedImage bi = ImageIO.read(src);   
            Image itemp = bi.getScaledInstance(width, height, BufferedImage.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, "jpg",out);   
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     
    /**
     * 对图片文件进行Base64编码,并加上DataURI前缀,可以直接在HTML中使用
     * @param imageFile
     * @return
     * @throws IOException
     */
    public static String base64EncodeAsDataURI(File imageFile) throws IOException{
        return "data:image/png;base64,"+base64Encode(imageFile);
    }
    /**
     * 对图片文件进行Base64编码
     * @param imageFile
     * @return
     * @throws IOException
     */
    public static String base64Encode(File imageFile) throws IOException{
        byte[] data = FileUtils.readFileToByteArray(imageFile);
        return base64Encode(data);
    }
    /**
     * 对图片文件进行Base64编码
     * @param image
     * @return
     * @throws IOException
     */
    public static String base64Encode(byte[] image) throws IOException{
        return Base64.encodeBase64String(image);
    }
    /**
     * 对图片文件进行Base64编码
     * @param fileAbsPath
     * @return
     * @throws IOException
     */
    public static String base64Encode(String fileAbsPath) throws IOException{
        return base64Encode(new File(fileAbsPath));
    }
    /**
     * 对图片文件进行Base64编码
     * @param image
     * @return
     * @throws IOException
     */
    public static String base64Encode(InputStream image) throws IOException{
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(image, output);
        return base64Encode(output.toByteArray());
    }
    /**
     * 把Base64解码为byte[],然后写到输出流
     * @param imgStr            转换为图片的字符串
     * @param imgCreatePath     将64编码生成图片的路径
     * @throws IOException 
     */
    public static void base64Decode(String imgData, OutputStream out) throws IOException{
        byte[] b = Base64.decodeBase64(imgData);
        out.write(b);out.close();
    }
    /**
     * 把Base64解码为byte[],然后写到文件中
     * @param imgData
     * @param out
     * @throws IOException
     */
    public static void base64Decode(String imgData, File file) throws IOException{
        base64Decode(imgData, new FileOutputStream(file));
    }
    /**
     * 把Base64解码为byte[],然后写到文件中
     * @param imgData
     * @param outAbsPath
     * @throws IOException
     */
    public static void base64Decode(String imgData, String fileAbsPath) throws IOException{
        base64Decode(imgData, new FileOutputStream(fileAbsPath));
    }
 
    public static void main(String[] args) throws IOException {
         
        /* 文字水印 */
        File file = new File("d:/abc/mpt8_2013122423341787.jpg");
        InputStream in = new FileInputStream(file);
        OutputStream out = new FileOutputStream("d:/abc/hello.jpg");
        watermark(in, out, "HelloWorld", "宋体", Font.BOLD, 72, Color.WHITE,100, 100, 0.5f);
         
    }

}

打开连接

ImageUtils.java:图片处理工具类[裁剪/图片水印/文字水印/缩放补白/Base64加密解密]相关推荐

  1. java 图片合成 工具类_Java图片合成工具类

    importjava.awt.Color;importjava.awt.Graphics2D;importjava.awt.image.BufferedImage;importjava.io.File ...

  2. 图片处理工具类 - ImageUtils.java

    纯JAVA实现的图片处理工具类,提供图片的裁剪.压缩.获取尺寸.制作圆角等方法. 源码如下:(点击下载 -ImageUtils.java .FolderUtils.java .commons-io-2 ...

  3. java 图片合成 工具类_Java实现的微信图片处理工具类【裁剪,合并,等比例缩放等】...

    本文实例讲述了Java实现的微信图片处理工具类.分享给大家供大家参考,具体如下: 现在 外面核心,图片文章比较少,看了拷贝代码,而用不了,用相应jar包处理,很多等比例缩放,达不到 想要的给予的期望: ...

  4. java 图片image工具类,ImageUtil.java

    1.java 图片image工具类,ImageUtil.java package com.broadway.numpeople.utils;import java.awt.Color; import ...

  5. java图片处理工具类,很实用哦

    笔者以前在项目里要求处理图片,当时在博客里看到这篇不错的帖子,但是没有看到原作的出处,于是就不客气的转载下来了...同时感谢原创写出这么好的东西. 这个图像工具类可实现以下常用功能:缩放图像.切割图像 ...

  6. Java 上传图片至OSS并返回图片地址工具类可直接用

    OSS上传图片并返回图片地址工具类 OSS上传图片并且返回地址工具类 可以直接拿去用 后续会继续更新 需要注意的点: 下面代码里的@Value里的几个值我是放在application.yml文件里的, ...

  7. Java实现pdf转图片的工具类(三种方法实现PDF转图片的案例)【亲测可用】

    提示:有些时候我们需要在项目中展示PDF,所以我们可以将PDF转为图片,然后已图片的方式展示,效果很好.Java使用各种技术将pdf转换成图片格式,并且内容不失帧.清晰可见,该工具类也是开发中常用到的 ...

  8. Android 图片处理工具类封装2

    http://www.2cto.com/kf/201312/263638.html Android 图片处理工具类封装 2013-12-10     0个评论   来源:Wiker Yong 的专栏  ...

  9. linux 图片编辑 java_Java的图片处理工具类

    Java的图片处理工具类: 可实现以下常用功能:缩放图像.切割图像.图像类型转换.彩色转黑白.文字水印.图片水印等 import java.awt.AlphaComposite; import jav ...

最新文章

  1. 非准确率至上,这些趋势在2020年的AI领域更受关注
  2. 文件监视器——Filemon
  3. 2020年,从提升认知开始
  4. python 有序字典_(Python基础教程之十七)Python OrderedDict –有序字典
  5. TensorFlow 实现深度神经网络 —— Denoising Autoencoder
  6. 【Java集合系列一】ArrayList解析
  7. 【Foreign】Weed [线段树]
  8. 词霸豆豆 — 互联网时代的金山词霸
  9. C语言实验——简单排序
  10. 找不到本地计算机策略组,Win10家庭版找不到本地组策略gpedit.msc解决办法
  11. 《代码大全》读书笔记之一
  12. Arcanist用法简介
  13. 烤仔TVのCCW丨密码学通识(五)消息认证码
  14. 精简系统登录页模板html+vue+elementui
  15. [医学图像分割综述] Medical Image Segmentation Using Deep Learning: A Survey
  16. python_安居客区域房源均价工具(matplotlib)
  17. php 解析 %e5%80%aa%e9%a3%9e,content.json
  18. AutoLISP确定图纸幅面DCL对话框设计
  19. 学习C语言的第一步安装
  20. 圆桌对话 | 详解2022全域营销的应用趋势和机会

热门文章

  1. R语言-数据整形之简介
  2. OpenJTAG与JLink的区别比较
  3. jQuery实现字体变大和缩小
  4. XPath最通俗的教程(ZZ)
  5. 指针和和一般的数据传递
  6. 11-JSP开发模型
  7. java使用hashset_Java集合(二)HashSet的使用
  8. linux磁盘iops限制,linux – 我需要多少IOPS?我的工作量瓶颈是存储
  9. 辐流式重力浓缩池计算_注册考试重点!平流式、竖流式、辐流式、斜板式4大沉淀池构型...
  10. spring数据字典_Redis为什么默认16个数据库?