java 自动生成略缩图示例代码
发布时间:2021-11-11 01:27:37
标签:java,自动生成,略缩图
当你要做一个图库的项目时,对图片大小、像素的控制是首先需要解决的难题。
一、单图生成略缩图
单图经过重新绘制,生成新的图片。新图可以按一定比例由旧图缩小,也可以规定其固定尺寸。
详细代码如下:
<SPAN style="FONT-SIZE: 14px">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);
}
}</SPAN>
当你把上面的代码移至myEclipse时,可能会在引入一下工具包时出错。
<SPAN style="FONT-SIZE: 14px">import com.sun.image.codec.</SPAN>
解决方法:只要把Windows - Preferences - Java - Compiler - Errors/Warnings里面的Deprecated and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。
二、批量生成略缩图
批量生成略缩图,即将已知文件夹中后缀为.jpg 或其他图片后缀名的文件 统一转化后 放到 已定的另外文件夹中
<SPAN style="FONT-SIZE: 14px">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);
}
}
}</SPAN>


猜你喜欢
- 之前写过一篇 Java 线程池的使用介绍文章《线程池全面解析》,全面介绍了什么是线程池、线程池核心类、线程池工作流程、线程池分类、拒绝策略、
- java 基础之JavaBean属性命名规范问题JavaBean属性名要求:前两个字母要么都大写,要么都小写下面我们来找找如果不遵循这个规范
- 一、项目简述本系统功能包括:数据统计、收件录入、发件录入、到件录入、派件录入、问题件录入、退件录入、留仓录入、装车录入、发车录入、到车录入、
- 文档合并是一种高效文档处理方式。如果能够有一个方法能将多种不同类型的文档合并成一种文档格式,那么在文档存储管理上将为我们提供极大的便利。因此
- 本文实例讲述了C#(asp.net)多线程用法。分享给大家供大家参考,具体如下:using System;using System.Coll
- hadoop做的一个简单grep程序,可从文档中提取包含某些字符串的行/* * 一个简单grep程序,可从文档中提取包含莫些字符串
- 一、微信官方文档微信支付开发流程(公众号支付)首先我们到微信支付的官方文档的开发步骤部分查看一下需要的设置。[图片上传失败...(image
- 一、Stream流介绍在JDK8时,JAVA新增了lambda表达式,它与 java.io 包里的 InputStream和 OutputS
- 有时,通过Runtime.getRuntime().exec()执行命令的有效负载有时会失败。使用Web Shell,反序列化利用或通过其他
- 在Android开发中,我们经常使用列表控件,而有时候列表控件条目中又会是多条目数据,这时候,我们无法确定每个条目的数据多少,而为了美观,我
- c++回调之利用函数指针示例#include <iostream>using namespace std;/**********
- 测试1@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.NANOSECOND
- 简介MapStruct 是一个代码生成器(可以生成对象映射转换的代码),它基于约定优于配置的方法,极大地简化了 Java bean 类型之间
- 网上看了很多篇文章关于如何配置mybatis的logback日志的,复杂的简单的都有,但是有用的没几个,耽误了很多时间。通过对logback
- bean 的生命周期对象创建实例化Bean对象,默认选择无参构造方法,如果只有一个有参构造那么调用有参构造,如果只有多个有参构造那么报错,除
- 下面由我来给大家展示用spring aop实现 * 的例子(电脑打印)下面就看一下具体的代码:先定义一个打印机的接口package aop
- 本文为大家分享了Android网络连接判断与相关处理,供大家参考,具体内容如下获取网络信息需要在AndroidManifest.xml文件中
- 首先我们要知道,主要系统服务都是在 SystemServer 启动的,蓝牙也是如此:1、SystemServer源码路径:/framewor
- 今天安装了jdk1.8、tomcat8、和maven3.5.2,弄好后在myeclipse新建了一个maven项目,项目默认是jdk1.5,
- 本文介绍了如何使用缓存来提高UI的载入输入和滑动的流畅性。使用内存缓存、使用磁盘缓存、处理配置改变事件等方法将会有效的解决这个问题。在您的U