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

本文实例讲述了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程序设计有所帮助。

(0)

相关推荐

  • Java通过jersey实现客户端图片上传示例

    在上一篇笔记 <SpringMVC实现图片上传>记录了将图片上传到本地的实现,在很多项目中都会有一台专门的文件服务器来保存文件的,这边记录下客户端通过jersey上传图片到文件服务端的实现. 由于要在不同主机上上传文件,所以不能直接通过流的方式来写,需要通过webService来完成,jersey是基于Java的一个轻量级RESTful风格的Web Services框架,它让客户端文件上传变得更简单. 1. maven依赖 spring的一些包以及fileupload和io包这边就不贴出来了.

  • Java以struts2为例介绍如何实现图片上传

    总的说图片上传有两种方式,一种是把图片文件写到数据库中,另一种是存到服务器文件目录中.写到数据库中的图片文件需要转换成二进制流的格式,占用数据库空间比较,适合少量图片的存储,比如说,系统中某些小图标,写到数据库中的优点是比较安全,不容易被用户不小心删除. 在struts2中实现(以图片上传为例) 1.FileUpload.jsp代码清单如下: <%@ page language="java" import="java.util.*" pageEncoding=

  • java实现图片裁切的工具类实例

    本文实例讲述了java实现图片裁切的工具类.分享给大家供大家参考,具体如下: package com.yanek.util; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import javax.im

  • java web图片上传和文件上传实例

    图片上传和文件上传本质上是一样的,图片本身也是文件.文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作. 注意事项 1.form表单一定要写属性enctype="multipart/form-data" 2.为了能保证文件能上传成功file控件的name属性值要和你提交的控制层变量名一致, 例如空间名是file那么你要在后台这样定义 private File file; //file控件名 private String fileContentType;//图

  • Java图片上传实现代码

    本文实例为大家分享了Java图片上传代码,供大家参考,具体内容如下 import java.io.*; import java.net.*; /* *发送端 */ class picsend { public static void main(String[] args) throws Exception { if(args.length!=1) { System.out.println("请选择一张.jpg图片"); return; } File file = new File(ar

  • 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.Re

  • Java实现图片上传到服务器并把上传的图片读取出来

    在很多的网站都可以实现上传头像,可以选择自己喜欢的图片做头像,从本地上传,下次登录时可以直接显示出已经上传的头像,那么这个是如何实现的呢? 下面说一下我的实现过程(只是个人实现思路,实际网站怎么实现的不太清楚) 实现的思路: 工具:MySQL,eclipse 首先,在MySQL中创建了两个表,一个t_user表,用来存放用户名,密码等个人信息, 一个t_touxiang表,用来存放上传的图片在服务器中的存放路径,以及图片名字和用户ID, T_touxiang表中的用户ID对应了t_user中的i

  • Java实现的图片上传工具类完整实例

    本文实例讲述了Java实现的图片上传工具类.分享给大家供大家参考,具体如下: package com.gcloud.common; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; /** * 图片上传工具类 * Created by charlin on 2017/9/10. */ public class UploadImageUtil { private String f

  • java通过模拟post方式提交表单实现图片上传功能实例

    本文实例讲述了java通过模拟post方式提交表单实现图片上传功能.分享给大家供大家参考,具体如下: 模拟表单html如下: <form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1"> <label> <input type="tex

  • Java+mysql本地图片上传数据库及下载示例

    做一个将本地图片上传到mysql数据库的小实例,顺便也下载下来到桌面检测是否上传成功. 在写代码之前得先在数据库中建立image表,用来存储图片. create table image (id int primary key auto_increment , name varchar(30) COMMENT '名称', content mediumblob COMMENT '图片'); 下面直接上代码: package jdbc_imagetest; import java.io.*; impo

  • java图片压缩工具类

    直接上java图片压缩code: import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class ImageProcess { /** * 图片 */ private I

随机推荐