当你要做一个图库的项目时,对图片大小、像素的控制是首先需要解决的难题。

本篇文章,在前辈的经验基础上,分别对单图生成略缩图和批量生成略缩图做个小结。

一、单图生成略缩图

单图经过重新绘制,生成新的图片。新图可以按一定比例由旧图缩小,也可以规定其固定尺寸。

详细代码如下:

import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Map; public class PicChange { /**
* @param im 原始图像
* @param resizeTimes 需要缩小的倍数,缩小2倍为原来的1/2 ,这个数值越大,返回的图片越小
* @return 返回处理后的图像
*/
public BufferedImage resizeImage(BufferedImage im, float resizeTimes) {
/*原始图像的宽度和高度*/
int width = im.getWidth();
int height = im.getHeight(); /*调整后的图片的宽度和高度*/
int toWidth = (int) (Float.parseFloat(String.valueOf(width)) / resizeTimes);
int toHeight = (int) (Float.parseFloat(String.valueOf(height)) / resizeTimes); /*新生成结果图片*/
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
return result;
} /**
* @param im 原始图像
* @param resizeTimes 倍数,比如0.5就是缩小一半,0.98等等double类型
* @return 返回处理后的图像
*/
public BufferedImage zoomImage(BufferedImage im, float resizeTimes) {
/*原始图像的宽度和高度*/
int width = im.getWidth();
int height = im.getHeight(); /*调整后的图片的宽度和高度*/
int toWidth = (int) (Float.parseFloat(String.valueOf(width)) * resizeTimes);
int toHeight = (int) (Float.parseFloat(String.valueOf(height)) * resizeTimes); /*新生成结果图片*/
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
return result;
} public boolean writeHighQuality(BufferedImage im, String fileFullPath) {
try {
/*输出到文件流*/
FileOutputStream newimage = new FileOutputStream(fileFullPath+System.currentTimeMillis()+".jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
/* 压缩质量 */
jep.setQuality(1f, true);
encoder.encode(im, jep);
/*近JPEG编码*/
newimage.close();
return true;
} catch (Exception e) {
return false;
}
} public static void main(String[] args) throws Exception{ String inputFoler = "F:\\pic" ;
/*这儿填写你存放要缩小图片的文件夹全地址*/
String outputFolder = "F:\\picNew\\";
/*这儿填写你转化后的图片存放的文件夹*/
float times = 0.25f;
/*这个参数是要转化成的倍数,如果是1就是转化成1倍*/ PicChange r = new PicChange(); File ff = new File("F:\\pic\\Chrysanthemum1.jpg");
BufferedImage f = javax.imageio.ImageIO.read(ff);
r.writeHighQuality(r.zoomImage(f,times), outputFolder); }
}

当你把上面的代码移至myEclipse时,可能会在引入一下工具包时出错。

import com.sun.image.codec.

解决方法:只要把Windows - Preferences - Java - Compiler - Errors/Warnings里面的Deprecated and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。

二、批量生成略缩图

批量生成略缩图,即将已知文件夹中后缀为.jpg 或其他图片后缀名的文件  统一转化后 放到 已定的另外文件夹中

import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Map; public class ResizeImage { /**
* @param im 原始图像
* @param resizeTimes 需要缩小的倍数,缩小2倍为原来的1/2 ,这个数值越大,返回的图片越小
* @return 返回处理后的图像
*/
public BufferedImage resizeImage(BufferedImage im, float resizeTimes) {
/*原始图像的宽度和高度*/
int width = im.getWidth();
int height = im.getHeight(); /*调整后的图片的宽度和高度*/
int toWidth = (int) (Float.parseFloat(String.valueOf(width)) / resizeTimes);
int toHeight = (int) (Float.parseFloat(String.valueOf(height)) / resizeTimes); /*新生成结果图片*/
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
return result;
} /**
* @param im 原始图像
* @param resizeTimes 倍数,比如0.5就是缩小一半,0.98等等double类型
* @return 返回处理后的图像
*/
public BufferedImage zoomImage(BufferedImage im, float resizeTimes) {
/*原始图像的宽度和高度*/
int width = im.getWidth();
int height = im.getHeight(); /*调整后的图片的宽度和高度*/
int toWidth = (int) (Float.parseFloat(String.valueOf(width)) * resizeTimes);
int toHeight = (int) (Float.parseFloat(String.valueOf(height)) * resizeTimes); /*新生成结果图片*/
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
return result;
} /**
* @param path 要转化的图像的文件夹,就是存放图像的文件夹路径
* @param type 图片的后缀名组成的数组
* @return
*/
public List<BufferedImage> getImageList(String path, String[] type) throws IOException{
Map<String,Boolean> map = new HashMap<String, Boolean>();
for(String s : type) {
map.put(s,true);
}
List<BufferedImage> result = new ArrayList<BufferedImage>();
File[] fileList = new File(path).listFiles();
for (File f : fileList) {
if(f.length() == 0)
continue;
if(map.get(getExtension(f.getName())) == null)
continue;
result.add(javax.imageio.ImageIO.read(f));
}
return result;
} /**
* 把图片写到磁盘上
* @param im
* @param path eg: C://home// 图片写入的文件夹地址
* @param fileName DCM1987.jpg 写入图片的名字
* @return
*/
public boolean writeToDisk(BufferedImage im, String path, String fileName) {
File f = new File(path + fileName);
String fileType = getExtension(fileName);
if (fileType == null)
return false;
try {
ImageIO.write(im, fileType, f);
im.flush();
return true;
} catch (IOException e) {
return false;
}
} public boolean writeHighQuality(BufferedImage im, String fileFullPath) {
try {
/*输出到文件流*/
FileOutputStream newimage = new FileOutputStream(fileFullPath+System.currentTimeMillis()+".jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
/* 压缩质量 */
jep.setQuality(1f, true);
encoder.encode(im, jep);
/*近JPEG编码*/
newimage.close();
return true;
} catch (Exception e) {
return false;
}
} /**
* 返回文件的文件后缀名
* @param fileName
* @return
*/
public String getExtension(String fileName) {
try {
return fileName.split("\\.")[fileName.split("\\.").length - 1];
} catch (Exception e) {
return null;
}
} public static void main(String[] args) throws Exception{ String inputFoler = "F:\\pic" ;
/*这儿填写你存放要缩小图片的文件夹全地址*/
String outputFolder = "F:\\picNew\\";
/*这儿填写你转化后的图片存放的文件夹*/
float times = 0.25f;
/*这个参数是要转化成的倍数,如果是1就是转化成1倍*/ ResizeImage r = new ResizeImage();
List<BufferedImage> imageList = r.getImageList(inputFoler,new String[] {"jpg"});
for(BufferedImage i : imageList) {
r.writeHighQuality(r.zoomImage(i,times),outputFolder);
}
}
}

解决完像素问题 接下来 期待

下文:为图片加水印

java自动生成略缩图的更多相关文章

  1. java,图片压缩,略缩图

    在网上找了两个图片的缩放类,在这里分享一下: package manager.util; import java.util.Calendar; import java.io.File; import ...

  2. php 制作略缩图

    一.需求 最近公司的项目中有个需求,就是用户上传自己的微信二维码,然后系统会自动将用户的微信二维码合并到产品中 二.分析 因为该系统是手机端的,所以从用户端的体验出发,用户当然是直接在微信上保存二维码 ...

  3. 设计数据库 ER 图太麻烦?不妨试试这两款工具,自动生成数据库 ER 图!!!

    忙,真忙 点赞再看,养成习惯,微信搜索『程序通事』,关注就完事了! 点击查看更多精彩的文章 这两个星期真是巨忙,年前有个项目因为各种莫名原因,一直拖到这个月才开始真正测试.然后上周又接到新需求,马不停 ...

  4. JAVA自动生成正则表达式工具类

    经过很久的努力,终于完成了JAVA自动生成正则表达式工具类.还记得之前需要正则,老是从网上找吗?找了想修改也不会修改.现在不用再为此烦恼了,使用此生成类轻松搞定所有正则表达式.赶快在同事面前炫一下吧. ...

  5. Mybatis上路_06-使用Java自动生成[转]

    Mybatis上路_06-使用Java自动生成 11人收藏此文章, 我要收藏发表于1个月前(2013-04-24 23:05) , 已有151次阅读 ,共0个评论 目录:[ - ] 1.编写Gener ...

  6. Bootstrap-CL:略缩图

    ylbtech-Bootstrap-CL:略缩图 1.返回顶部 1. Bootstrap 缩略图 本章将讲解 Bootstrap 缩略图.大多数站点都需要在网格中布局图像.视频.文本等.Bootstr ...

  7. java 自动生成四则运算式

    本篇文章将要介绍一个“自动生成四则运算式”的java程序,在没有阅读<构建之法>之前,我已经通过一个类的形式实现了要求的功能,但是当阅读完成<构建之法>之后,我意识到自己所写程 ...

  8. Mybatis上路_06-使用Java自动生成

    目录[-] 1.编写Generator执行配置文件: 2.在MyEclipse中建空web项目: 3.编写并执行Java程序: 4.查看并修改生成的文件: 5.测试,使用生成的文件查询: 1)导入My ...

  9. java自动生成entity文件

    网上关于自动生成entity文件的代码很多,看了很多代码后,在先辈们的基础上再完善一些功能(指定多个表,全部表). 为了使用方便所以把两个类写在一个java文件中,所以大家可以直接拿这个java文件, ...

随机推荐

  1. STL在迭代的过程,删除指定的元素

    直接在Code.在 Picture #include <iostream> #include <list> using namespace std; // STL在迭代的过程中 ...

  2. Linux经常使用命令(一) - ls

    ls命令是linux下最经常使用的命令.ls命令就是list的缩写, 缺省下ls用来打印出当前文件夹的清单, 假设ls指定其它文件夹, 那么就会显示指定文件夹里的文件及文件夹清单. 通过ls 命令不仅 ...

  3. 第1章1节《MonkeyRunner源码剖析》概述:前言(原创)

    天地会珠海分舵注:本来这一系列是准备出一本书的,详情请见早前博文“寻求合作伙伴编写<深入理解 MonkeyRunner>书籍“.但因为诸多原因,没有如愿.所以这里把草稿分享出来,所以错误在 ...

  4. C# 笔试题,看你会几道题

    1.       Which interface you need to implement to support for each? IEnumerator IEnumerable ICompare ...

  5. openwrt_git_pull命令提示merger冲突时如何解决?

    直接贴代码 tf@ubuntu:~/projects/openwrt1407$ git pull Updating 331ecb0..d12dc6e error: Your local changes ...

  6. 手机发送短信JS验证

    function tj() { var phone = jQuery('#phone').val(); var code = jQuery('#verificationcode').val(); va ...

  7. C#的StringBuilder 以及string字符串拼接的效率对照

    今天公司一个做Unity3d的人在说字符串拼接的一个效率问题,他觉得string拼接会产生新的一个内存空间,假设不及时回收会产生大量的碎片,特别是在Unity3d这样一个Updata环境下,由于每一帧 ...

  8. Varnish缓存服务

    Varnish缓存服务详解及应用实现   1.varnish的基本介绍   Varnish 的作者Poul-Henning Kamp是FreeBSD的内核开发者之一,他认为现在的计算机比起1975年已 ...

  9. Reactive Extensions

    Rx提供了一种新的组织和协调异步事件的方式,极大的简化了代码的编写.Rx最显著的特性是使用可观察集合(Observable Collection)来达到集成异步(composing asynchron ...

  10. Yeoman入门之安装及环境配置

    Yeoman入门之安装及环境配置 http://blog.csdn.net/panlingfan/article/details/27345037 http://www.nodejs.orgYEOMA ...