Java基于装饰者模式实现的图片工具类实例【附demo源码下载】

发布时间 - 2026-01-11 03:07:41    点击率:

本文实例讲述了Java基于装饰者模式实现的图片工具类。分享给大家供大家参考,具体如下:

ImgUtil.java:

/*
 * 装饰者模式实现图片处理工具类
 * 类似java的io流 - 
 * Img类似低级流可以独立使用
 * Press和Resize类似高级流
 * 需要依赖于低级流
 */
package util;
import java.io.File;
import java.util.List;
/**
 * 图片工具类(装饰者)和图片(被装饰者)的公共接口
 * @author xlk
 */
public interface ImgUtil {
  /** 装饰方法 - 处理图片 */
  List<File> dispose();
}

AbstractImgUtil.java:

package util;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
/**
 * 抽象图片工具类 - 抽象装饰者
 * @author xlk
 */
public abstract class AbstractImgUtil implements ImgUtil {
  private ImgUtil imgUtil;
  @Override
  public List<File> dispose() {
    return imgUtil.dispose();
  }
  public AbstractImgUtil(){}
  public AbstractImgUtil(ImgUtil imgUtil) {
    this.imgUtil = imgUtil;
  }
  /**
   * 判断文件是不是图片
   * @param file 被判断的文件
   * @return 图片返回true 非图片返回false
   * @throws IOException 
   */
  public static boolean isImg(File file) {
    if (file.isDirectory()) {
      return false;
    }
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(file);
      Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
      if (!iter.hasNext()) {//文件不是图片
        return false;
      }
      return true;
    } catch (IOException e) {
      return false;
    }
  }
}

Press.java:

package util;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
/**
 * 加水印 - 装饰者
 * @author xlk
 */
public class Press extends AbstractImgUtil {
  private  List<File>  src;   //图片路径集合
  private  String    waterImg;//水印图片路径
  private  Integer    x;     //水印图片距离目标图片左侧的偏移量, 如果x<0, 则在正中间
  private  Integer    y;     //水印图片距离目标图片上侧的偏移量, 如果y<0, 则在正中间
  private  float    alpha;   //水印透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
  @Override
  public List<File> dispose() {
    src = super.dispose();
    return press();
  }
  /** 加水印 - 具体装饰方法 */
  private List<File> press() {
    if (waterImg==null || "".equals(waterImg)) {
      throw new RuntimeException("水印路径不能为空");
    }
    if (!isImg(new File(waterImg))) {
      throw new RuntimeException("水印路径所指向的文件不是图片");
    }
    if (src.size()<=0) {
      return src;
    }
    if (x!=null && y!=null) {
      for (File f: src) {
        press(f.getPath(), waterImg, f.getParent(), x, y, alpha);
      }
    } else {
      for (File f: src) {
        press(f.getPath(), waterImg, f.getParent(), alpha);
      }
    }
    return src;
  }
  public Press() {}
  public Press(ImgUtil imgUtil, String waterImg, float alpha) {
    super(imgUtil);
    this.waterImg = waterImg;
    this.alpha = alpha;
  }
  public Press(ImgUtil imgUtil, String waterImg, Integer x, Integer y, float alpha) {
    super(imgUtil);
    this.waterImg = waterImg;
    this.x = x;
    this.y = y;
    this.alpha = alpha;
  }
  public String getWaterImg() {
    return waterImg;
  }
  public void setWaterImg(String waterImg) {
    this.waterImg = waterImg;
  }
  public Integer getX() {
    return x;
  }
  public void setX(Integer x) {
    this.x = x;
  }
  public Integer getY() {
    return y;
  }
  public void setY(Integer y) {
    this.y = y;
  }
  public float getAlpha() {
    return alpha;
  }
  public void setAlpha(float alpha) {
    this.alpha = alpha;
  }
  /** 添加图片水印 */
  private static void press(String src, String waterImg, String target, int x, int y, float alpha) {
    File newFile = null;
    try {
      File file = new File(src);
      Image image = ImageIO.read(file);
      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(new File(waterImg)); // 水印文件
      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();
      
      File dir = new File(target);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      newFile = new File(target + File.separator + file.getName());
      ImageIO.write(bufferedImage, "jpg", newFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** 平铺添加图片水印 */
  private static void press(String src, String waterImg, String target, float alpha) {
    File newFile = null;
    try {
      File file = new File(src);
      Image image = ImageIO.read(file);
      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(new File(waterImg)); // 水印文件
      int width_1 = waterImage.getWidth(null);
      int height_1 = waterImage.getHeight(null);
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
      
      int rpt_x = width>width_1?(int)Math.ceil(Double.valueOf(width)/width_1):1;//x方向重复次数
      int rpt_y = height>height_1?(int)Math.ceil(Double.valueOf(height)/height_1):1;//y方向重复次数
      for (int i=0; i<rpt_x; i++) {
        for (int j=0; j<rpt_y; j++) {
          g.drawImage(waterImage, i*width_1, j*height_1, width_1, height_1, null);
        }
      }// 水印文件结束
      g.dispose();
      
      File dir = new File(target);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      newFile = new File(target + File.separator + file.getName());
      ImageIO.write(bufferedImage, "jpg", newFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Resize.java:

package util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
/**
 * 缩放 - 装饰者
 * @author xlk
 */
public class Resize extends AbstractImgUtil {
  /** 比例不同边界颜色 */
  private static final Color color = new Color(230,230,230);
  private  List<File>  src;  //图片路径集合
  private  int      height;  //处理后高度
  private int      width;  //处理后宽度
  private double    ratio;  //处理后高宽比
  private boolean    bb;    //比例不对时是否补白
  @Override
  public List<File> dispose() {
    src = super.dispose();
    return resize();
  }
  /** 缩放 - 具体装饰方法 */
  private List<File> resize() {
    if (src.size()<=0) {
      return src;
    }
    if (ratio>0) {
      for (File f: src) {
        resize(f.getPath(), f.getParent(), ratio, bb);
      }
    } else if (height>0 && width>0) {
      for (File f: src) {
        resize(f.getPath(), f.getParent(), height, width, bb);
      }
    }
    return src;
  }
  public Resize() {}
  public Resize(ImgUtil imgUtil, int height, int width, boolean bb) {
    super(imgUtil);
    this.height = height;
    this.width = width;
    this.bb = bb;
  }
  public Resize(ImgUtil imgUtil, double ratio, boolean bb) {
    super(imgUtil);
    this.ratio = ratio;
    this.bb = bb;
  }
  public int getHeight() {
    return height;
  }
  public void setHeight(int height) {
    this.height = height;
  }
  public int getWidth() {
    return width;
  }
  public void setWidth(int width) {
    this.width = width;
  }
  public double getRatio() {
    return ratio;
  }
  public void setRatio(double ratio) {
    this.ratio = ratio;
  }
  public boolean isBb() {
    return bb;
  }
  public void setBb(boolean bb) {
    this.bb = bb;
  }
  /** 图片缩放-按照尺寸 */
  private static void resize(String src, String target, int height, int width, boolean bb) {
    File newFile = null;
    try {
      double ratio = 0; //缩放比例
      File f = new File(src);
      BufferedImage bi = ImageIO.read(f);
      Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
      //计算比例
      if (Double.valueOf(bi.getHeight())/bi.getWidth() > Double.valueOf(height)/width) {
        ratio = Double.valueOf(height) / bi.getHeight();
      } else {
        ratio = Double.valueOf(width) / 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);
        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, null);
        else
          g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), color, null);
        g.dispose();
        itemp = image;
      }
      
      File dir = new File(target);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      newFile = new File(target + File.separator + f.getName());
      ImageIO.write((BufferedImage) itemp, "jpg", newFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** 图片缩放-按照高宽比 */
  private static void resize(String src, String target, double ratio, boolean bb) {
    File newFile = null;
    try {
      File f = new File(src);
      BufferedImage bi = ImageIO.read(f);
      //计算尺寸
      int width = bi.getWidth();
      int height = bi.getHeight();
      if (Double.valueOf(height)/width<ratio) {
        height = (int)(width*ratio);
      } else {
        width = (int)(Double.valueOf(height)/ratio);
      }
      Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
      AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(1, 1), 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);
        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, null);
        else
          g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), color, null);
        g.dispose();
        itemp = image;
      }
      
      File dir = new File(target);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      newFile = new File(target + File.separator + f.getName());
      ImageIO.write((BufferedImage) itemp, "jpg", newFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Img.java:

package util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 图片 - 原组件
 * @author xlk
 */
public class Img implements ImgUtil {
  private  String  src;  //源图片或图片文件夹路径
  private  String  target;  //目标文件夹路径
  private  boolean  inner;  //true-包含子文件夹, false-仅当前文件夹
  @Override
  public List<File> dispose() {
    return copy();
  }
  /** 复制 - 被装饰者初始状态 */
  private List<File> copy() {
    if (src==null || "".equals(src) || target==null || "".equals(target)) {
      throw new RuntimeException("源路径或目标路径不能为空");
    }
    File srcFile = new File(src);
    List<File> list = new ArrayList<File>();
    
    File targetDir = new File(target);
    if (!targetDir.exists()) {
      targetDir.mkdirs();
    }
    a:
    if (srcFile.isDirectory()) {//源路径是文件夹
      File[] subs = srcFile.listFiles();
      if (subs.length<=0) {
        break a;
      }
      for (File sub: subs) {
        if (sub.isDirectory() && inner) {
          list.addAll(new Img(sub.getPath(), target+File.separator+sub.getName(), true).copy());
        } else if (AbstractImgUtil.isImg(sub)) {
          list.add(copy(sub, target));
        }
      }
    } else if (AbstractImgUtil.isImg(srcFile)) {//源路径是图片
      list.add(copy(srcFile, target));
    }
    return list;
  }
  private File copy(File file, String target) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    File newFile = null;
    try {
      fis = new FileInputStream(file);
      newFile = new File(target + File.separator + file.getName());
      fos = new FileOutputStream(newFile);
      byte[] bs = new byte[1024*10];
      int len = -1;
      while ((len=fis.read(bs))!=-1) {
        fos.write(bs, 0, len);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (fis!=null) {
          fis.close();
        }
        if (fos!=null) {
          fos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return newFile;
  }
  public Img() {}
  public Img(String src, String target) {
    this.src = src;
    this.target = target;
  }
  public Img(String src, String target, boolean inner) {
    this.src = src;
    this.target = target;
    this.inner = inner;
  }
  public String getSrc() {
    return src;
  }
  public void setSrc(String src) {
    this.src = src;
  }
  public String getTarget() {
    return target;
  }
  public void setTarget(String target) {
    this.target = target;
  }
  public boolean isInner() {
    return inner;
  }
  public void setInner(boolean inner) {
    this.inner = inner;
  }
}

附:完整实例代码点击此处本站下载

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。


# Java  # 装饰者模式  # 图片  # 工具类  # Java设计模式之装饰者模式详解  # Java设计模式之java装饰者模式详解  # java设计模式-装饰者模式详解  # Java基于装饰者模式实现的染色馒头案例详解  # 23种设计模式(6)java装饰者模式  # Java装饰者模式的深入了解  # 则在  # 程序设计  # 为空  # 进阶  # 操作技巧  # 正中间  # 偏移量  # 相关内容  # 平铺  # 感兴趣  # 数据结构  # 高宽比  # 给大家  # 点击此处  # 被判  # 所述  # 面向对象  # 不透明  # 图片处理  # 讲述了 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 高防服务器租用指南:配置选择与快速部署攻略  太平洋网站制作公司,网络用语太平洋是什么意思?  Laravel如何使用模型观察者?(Observer代码示例)  Python文件操作最佳实践_稳定性说明【指导】  在线ppt制作网站有哪些软件,如何把网页的内容做成ppt?  Laravel怎么处理异常_Laravel自定义异常处理与错误页面教程  微信小程序 wx.uploadFile无法上传解决办法  美食网站链接制作教程视频,哪个教做美食的网站比较专业点?  Laravel如何使用Vite进行前端资源打包?(配置示例)  Android GridView 滑动条设置一直显示状态(推荐)  JavaScript数据类型有哪些_如何准确判断一个变量的类型  在线制作视频的网站有哪些,电脑如何制作视频短片?  Laravel如何实现数据库事务?(DB Facade示例)  iOS UIView常见属性方法小结  手机网站制作平台,手机靓号代理商怎么制作属于自己的手机靓号网站?  Laravel如何使用Socialite实现第三方登录?(微信/GitHub示例)  微信小程序 HTTPS报错整理常见问题及解决方案  javascript中的数组方法有哪些_如何利用数组方法简化数据处理  香港服务器租用费用高吗?如何避免常见误区?  laravel怎么为API路由添加签名中间件保护_laravel API路由签名中间件保护方法  Windows10如何删除恢复分区_Win10 Diskpart命令强制删除分区  猎豹浏览器开发者工具怎么打开 猎豹浏览器F12调试工具使用【前端必备】  韩国网站服务器搭建指南:VPS选购、域名解析与DNS配置推荐  Edge浏览器怎么启用睡眠标签页_节省电脑内存占用优化技巧  Laravel模型事件有哪些_Laravel Model Event生命周期详解  Laravel如何设置定时任务(Cron Job)_Laravel调度器与任务计划配置  如何在VPS电脑上快速搭建网站?  JavaScript常见的五种数组去重的方式  三星网站视频制作教程下载,三星w23网页如何全屏?  如何选择PHP开源工具快速搭建网站?  Python数据仓库与ETL构建实战_Airflow调度流程详解  深圳防火门网站制作公司,深圳中天明防火门怎么编码?  黑客入侵网站服务器的常见手法有哪些?  Laravel如何实现本地化和多语言支持?(i18n教程)  Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】  Laravel怎么连接多个数据库_Laravel多数据库连接配置  Laravel API资源类怎么用_Laravel API Resource数据转换  Laravel怎么进行浏览器测试_Laravel Dusk自动化浏览器测试入门  英语简历制作免费网站推荐,如何将简历翻译成英文?  Laravel怎么做数据加密_Laravel内置Crypt门面的加密与解密功能  javascript中对象的定义、使用以及对象和原型链操作小结  如何在 Python 中将列表项按字母顺序编号(a.、b.、c. …)  Laravel的路由模型绑定怎么用_Laravel Route Model Binding简化控制器逻辑  java中使用zxing批量生成二维码立牌  如何在香港服务器上快速搭建免备案网站?  Laravel怎么导出Excel文件_Laravel Excel插件使用教程  Android滚轮选择时间控件使用详解  高端网站建设与定制开发一站式解决方案 中企动力  在线教育网站制作平台,山西立德教育官网?  Laravel集合Collection怎么用_Laravel集合常用函数详解