评论

收藏

[Java] 详解Java实现批量压缩图片裁剪压缩多种尺寸缩略图一键批量上传图片

编程语言 编程语言 发布于:2021-09-17 23:45 | 阅读数:479 | 评论:0

这篇文章主要介绍了Java实现批量压缩图片裁剪压缩多种尺寸缩略图一键批量上传图片,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
10万+it人都在关注的图片批量压缩上传方案(完整案例+代码)
背景需求:为了客户端访问图片资源时,加载图片更流畅,体验更好,通常不会直接用原图路径,需要根据不同的场景显示不同规格的缩略图,根据商品关键属性,能够获取到图片不同尺寸规格的图片路径,并且能根据不同缩略图直观看到商品的关键属性,需要写一个java小工具把本地磁盘中的图片资源一键上传至分布式fastdfs文件服务器,并把图片信息存入本地数据库,pc端或者客户端查询商品时,就可以根据商品的业务属性。比如根据productid就能把商品相关的不同尺寸规格的图片都获取到,页面渲染图片资源时,不同的场景,直接通过文件服务器的ip+存储路径,可以在线预览。
示例:商品id为1001的主图原图1001.jpg,大小为800×800(px),在本案例中解析为1001-50×50.jpg,1001-100×100.jpg,1001-200×200.jpg,1001-400×400.jpg,解析后连同原图就是5种尺寸规格的图片。前端就能直观的根据屏幕大小,业务场景等因素使用不同的图片。
实现思路:先把本地磁盘目录中的所有图片资源通过io流读出来,读到内存中,然后对图片的名称根据定义好的业务规则解析,生成不同的图片名,然后对原图进行不同规格的解析压缩处理,以及图片资源的上传和图片信息的批量保存至数据库。
常用的压缩方案有下面2种:
方案一:对原图进行按照指定存储空间的压缩,比如原图100kb,压缩至10kb
方案二:对原图进行指定宽高大小的压缩,比如原图800*800,压缩至100*100
准备工作:封装一个文件流操作的通过工具类,如下:
package com.demo.utils;
 
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
 
import org.apache.tomcat.util.codec.binary.base64;
 
/**
 * 创建时间:2019年3月13日 下午9:02:32
 * 项目名称:shsc-batchupload-server
 * 类说明:文件流工具类
 * @author guobinhui
 * @since jdk 1.8.0_51
 */
public class fileutils {
 
  /* 
   * 读取本地物理磁盘目录里的所有文件资源到程序内存 
   */ 
  public static list<file> readfiles(string filedir) {
  file dirpath = new file(filedir);
  //用listfiles()获得子目录和文件
  file[] files = dirpath.listfiles();
  list<file> list1 = new arraylist<file>();
  for (int i = 0; i < files.length; i++) {
   file file = files[i];
   if (!file.isdirectory()) {
    list1.add(files[i]);
    }
  }
   system.out.println("目录图片数量为:"+list1.size());
   return list1;
  }
  
  /* 
   * file文件流转为base64的字符串流
   * 注意:通过前端页面上传图片时,用 multipartfile文件流可以接收图片并上传,multipartfile流有很丰富的方法
   * 本案例通过后台小工具上传,需要把图片资源的文件流转为base64格式的流才可以上传
   */ 
  public static string getbase64(file file) {
  fileinputstream fis = null;
  string base64string = null;
  try {
    fis = new fileinputstream(file);
    byte[] buff = new byte[fis.available()];
    fis.read(buff);
    base64string = base64.encodebase64string(buff);
  } catch (filenotfoundexception e) {
    // todo auto-generated catch block
    e.printstacktrace();
  } catch (ioexception e) {
    // todo auto-generated catch block
    e.printstacktrace();
  }   finally{
    if(fis != null){
      try {
        fis.close();
      } catch (ioexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
    }
  }
  return base64string;
  }
  
  /**
  * 将file文件流转为字节数组
  * @param file
  * @return
  */
  public static byte[] getbyte(file file){
  byte[] bytes = null;
  try {
    fileinputstream fis = new fileinputstream(file);
    bytes = new byte[fis.available()];
    fis.read(bytes);
    fis.close();
  } catch (filenotfoundexception e) {
    e.printstacktrace();
  } catch (ioexception e) {
    e.printstacktrace();
  }
  return bytes;
  }
  
  /**
  * 将字节输出流写到指定文件
  * @param os
  * @param file
  */
  public static void writefile(bytearrayoutputstream os, file file){
  fileoutputstream fos = null;
  try {
    byte[] bytes = os.tobytearray();
    if (file.exists()) {
      file.delete();
    }
    fos = new fileoutputstream(file);
    fos.write(bytes);
  } catch (filenotfoundexception e) {
    e.printstacktrace();
  } catch (ioexception e) {
    e.printstacktrace();
  } finally {
    try {
      fos.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }
  }
}
封装一个压缩图片处理类
package com.demo.mapper.entity;
 
import java.awt.image;
import java.awt.geom.affinetransform;
import java.awt.image.affinetransformop;
import java.awt.image.bufferedimage;
import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import javax.imageio.imageio;
 
/**
 * 创建时间:2019年3月13日 下午3:35:05
 * 项目名称:shsc-batchupload-server
 * 类说明:图片压缩处理类
 * @author guobinhui
 * @since jdk 1.8.0_51
 */
public class imgcompress {
 
  private image img; 
  private int width; 
  private int height;
  
  /** 
   * 构造函数 
   */
  public imgcompress(string filepath) throws ioexception { 
  file file = new file(filepath);// 读入文件 
  img = imageio.read(file);   // 构造image对象 
  width = img.getwidth(null);  // 得到源图宽 
  height = img.getheight(null); // 得到源图长 
  } 
  public image getimg() {
    return img;
  }
  public void setimg(image img) {
    this.img = img;
  }
  public int getwidth() {
    return width;
  }
  public void setwidth(int width) {
    this.width = width;
  }
  public int getheight() {
    return height;
  }
  public void setheight(int height) {
    this.height = height;
  }
  public void resize(int w, int h,file file,string dir) throws ioexception { 
  // scale_smooth 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好,但是速度慢 
   bufferedimage tag = new bufferedimage(50,50,bufferedimage.type_int_rgb );
  image img = imageio.read(file);
  image image = img.getscaledinstance(w, h, image.scale_smooth);
  tag.getgraphics().drawimage(image,50, 50, null); // 绘制缩小后的图 
  
  // 将输入文件转换为字节数组
  byte[] bytes = fileutils.getbyte(file);
  // 构造输入输出字节流
  bytearrayinputstream is = new bytearrayinputstream(bytes);
  bytearrayoutputstream os = new bytearrayoutputstream();
  double rate = w/800;//缩放比率
  try {
   // 处理图片
   zoomimage(is,os,rate);
  } catch (exception e) {
   e.printstacktrace();
  }
  // 将字节输出流写入文件
  fileutils.writefile(os,new file(dir+"/"+file.getname()));
  } 
  
  public void zoomimage(inputstream is, outputstream os,double rate) throws exception { 
   bufferedimage bufimg = imageio.read(is);
   affinetransformop ato = new affinetransformop(affinetransform.getscaleinstance(rate,rate), null);
   bufferedimage bufferedimage = ato.filter(bufimg, null);
   imageio.write(bufferedimage, "jpg", os);
 }
}
方案一具体实现过程:
package com.demo.controller;
 
import java.awt.color;
import java.awt.graphics;
import java.awt.image;
import java.awt.image.bufferedimage;
import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;
 
import javax.imageio.imageio;
 
import org.apache.tomcat.util.codec.binary.base64;
import org.springframework.beans.beanutils;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.restcontroller;
import com.demo.mapper.entity.attachmentmodel;
import com.demo.mapper.entity.imgcompress;
import com.demo.mapper.entity.productpic;
import com.demo.service.ifileservice;
import com.demo.utils.fileutils;
import com.shsc.framework.common.resultinfo;
 
/**
 * 创建时间:2019年3月8日 下午3:03:56
 * 项目名称:shsc-batchupload-server
 * 类说明:图片批量压缩上传
 * @author guobinhui
 * @since jdk 1.8.0_51
 */
@restcontroller
@requestmapping(value="/file")
public class filecontroller {
 
 
@autowired
private ifileservice fileserviceimpl;
 
 
@requestmapping("/test")
@responsebody
public string test() {
 //原始图片目录
 string originalfiledir = "d:/pics/pic1";
 list <file> originalfilelist = readfiles(originalfiledir);
 iterator<file> it = originalfilelist.iterator();
 //压缩后的缩略图目录
 string thumbnaildir = "d:/uploadbasedir/productpic/20190313/thumbnail";
 long startwrite = system.currenttimemillis();
 while(it.hasnext()){
  file file = (file)it.next();
  try {
   imgcompress img = new imgcompress(file.getpath());
   img.resize(50, 50, file, thumbnaildir);
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
   return "上传失败!";
  }   
  }
 long endwrite = system.currenttimemillis();
 system.out.println("批量上传文件共计耗时:" +(endwrite-startwrite)/1000+"秒" );  
return "<h1 style='color:red;'>批量上传文件成功,非常棒,压缩上传文件总数量为:"+num+",共计耗时"+(endwrite-startwrite)/1000+"秒</h1>";
 } 
}
最后在浏览器上访问该接口或者把该接口放在main方法里run,效果如下:
DSC0000.png

方案二具体实现过程:
@requestmapping("/upload")
@responsebody
public string upload(){
  //win环境原始文件目录
  string originalfiledir = "d:/pics/pic1";
  system.out.println("读磁盘文件开始");
  long startread = system.currenttimemillis();
  list <file> originalfilelist = readfiles(originalfiledir);
  long endread = system.currenttimemillis();
  system.out.println("读磁盘文件结束");
  system.out.println("读取磁盘文件共计耗时:" +(endread-startread)+"毫秒" );   
  
  iterator<file> it = originalfilelist.iterator();
  system.out.println("压缩拷贝文件开始");
  long startwrite = system.currenttimemillis();
//  integer size = 500;//每500个图片批量插入一次
//  integer i = 0;
  string productnumber = null;
  
  string thumbnaildir = "d:/uploadbasedir/productpic/20190313/thumbnail";
  string base64 = null;
  string new50picname = "";
  string new100picname = "";
  string new200picname = "";
  string new400picname = "";
  list <productpic> piclist = new arraylist<productpic>();
  int pictype;
  list <integer> sizelist = new arraylist<integer>();
  sizelist.add(0,50);
  sizelist.add(1,100);
  sizelist.add(2,200);
  sizelist.add(3,400);
  
 while(it.hasnext()){
  file file = (file)it.next();
  system.out.println("原始文件路径为:"+file.getpath());
  string originalfilename= file.getname();
  string prefixname = originalfilename.substring(0,originalfilename.lastindexof("."));
  string ext = originalfilename.substring(originalfilename.lastindexof("."));
  
  byte[] buff = fileutils.getbyte(file);
  bytearrayinputstream is = new bytearrayinputstream(buff);
  bytearrayoutputstream os = null;
  bufferedimage bi = null;
  base64 = getbase64(file);
  resultinfo<?> r = fileserviceimpl.uploadbase64(base64,originalfilename);
  attachmentmodel att = (attachmentmodel)r.getdata();
  if(originalfilename.indexof('-') == -1) {
   pictype = 1;
   productnumber = prefixname;
  }else {
   pictype = 2;
   productnumber = originalfilename.substring(0,originalfilename.lastindexof("-"));
  }
  if(r.issuccess()) {
   productpic pic = new productpic();
   beanutils.copyproperties(att, pic);
   pic.getpicname();
   pic.setproductid(productnumber);
   pic.setpictype(pictype);
   piclist.add(pic);
  }
  if(originalfilename.indexof('-') == -1) {//不带'-'的是商品主图
   productnumber = prefixname;
   new50picname = productnumber+'-'+ "50×50"+ext;
   new100picname = productnumber+'-'+ "100×100"+ext;
   new200picname = productnumber+'-'+ "200×200"+ext;
   new400picname = productnumber+'-'+ "400×400"+ext;
  }else {
   productnumber = originalfilename.substring(0,originalfilename.lastindexof("-"));
   new50picname = originalfilename.substring(0,originalfilename.lastindexof("."))+'-'+ "50×50"+ext;
   new100picname = originalfilename.substring(0,originalfilename.lastindexof("."))+'-'+ "100×100"+ext;
   new200picname = originalfilename.substring(0,originalfilename.lastindexof("."))+'-'+ "200×200"+ext;
   new400picname = originalfilename.substring(0,originalfilename.lastindexof("."))+'-'+ "400×400"+ext;
  }
  
  try {
   file f = null;
   bi = imageio.read(is);
   for (int i = 0; i < sizelist.size(); i++) {
    os = new bytearrayoutputstream();
    image image = bi.getscaledinstance(sizelist.get(i),sizelist.get(i), image.scale_smooth);
    bufferedimage tag = new bufferedimage(sizelist.get(i),sizelist.get(i),bufferedimage.type_int_rgb);
    graphics g = tag.getgraphics();
    g.setcolor(color.red);
    g.drawimage(image, 0, 0, null); //绘制处理后的图
    g.dispose();
    imageio.write(tag, "jpg", os);
    if(sizelist.get(i) == 50) {
     fileutils.writefile(os,new file(thumbnaildir+"/"+new50picname));
     f = new file(thumbnaildir+"/"+new50picname);
    }else if(sizelist.get(i) == 100) {
     fileutils.writefile(os,new file(thumbnaildir+"/"+new100picname));
     f = new file(thumbnaildir+"/"+new100picname);
    }else if(sizelist.get(i) == 200) {
     fileutils.writefile(os,new file(thumbnaildir+"/"+new200picname));
     f = new file(thumbnaildir+"/"+new200picname);
    }else if(sizelist.get(i) == 400) {
     fileutils.writefile(os,new file(thumbnaildir+"/"+new400picname));
     f = new file(thumbnaildir+"/"+new400picname);
    }
    base64 = getbase64(f);
    resultinfo<?> rr = fileserviceimpl.uploadbase64(base64,f.getname());
    if(rr.issuccess()) {
      attachmentmodel atta = (attachmentmodel)rr.getdata();
      if(atta.getpicname().indexof('-') == -1) {//不带'-'的是商品主图
        pictype = 1;
      }else if(atta.getpicname().indexof("-1.") != -1
          || atta.getpicname().indexof("-2.") != -1
          || atta.getpicname().indexof("-3.") != -1
          || atta.getpicname().indexof("-4.") != -1) {
        pictype = 2;
      }else if((atta.getpicname().indexof("-1-") == -1
          ||atta.getpicname().indexof("-2-") == -1
          ||atta.getpicname().indexof("-3-") == -1
          ||atta.getpicname().indexof("-4-") == -1)
          && atta.getpicname().indexof("-") != -1) {
        pictype = 3;
      }else {
        pictype = 4;
      }
      productpic pic = new productpic();
      beanutils.copyproperties(atta, pic);
      pic.getpicname();
      pic.setproductid(productnumber);
      pic.setpictype(pictype);
      piclist.add(pic);
    }
  } 
  } catch (exception e1) {
    // todo auto-generated catch block
    e1.printstacktrace();
  }
}
int num = fileserviceimpl.insertpics(piclist);
if(num > 0) {
  long endwrite = system.currenttimemillis();
  system.out.println("批量上传文件共计耗时:" +(endwrite-startwrite)/1000+"秒" ); 
  return "<h1 style='color:red;'>批量上传文件成功,非常棒,压缩上传文件总数量为:"+num+",共计耗时"+(endwrite-startwrite)/1000+"秒</h1>";
}
return "批量上传文件失败!";
}
以上所述是小编给大家介绍的java实现批量压缩图片裁剪压缩多种尺寸缩略图一键批量上传图片详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对CodeAE代码之家网站的支持!
原文链接:https://blog.csdn.net/guobinhui/article/details/88540397

关注下面的标签,发现更多相似文章