/**
*
*/
package com.fkhwl.fkhserver.core.utils; import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder; /**
* @ClassName: ThumbnailTools
* @Description: 缩略图生成工具
* @author
* @date 2014年9月25日 下午5:18:33
*/
public class ThumbnailTools { private int fileSize;
private String inPath; // 输入图路径
private String outPath; // 输出图路径
private int width = 100; // 默认输出图片宽
private int height = 100; // 默认输出图片高
private String inFileName; // 输入图文件名
private String outFileName; // 输出图文件名
private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
private String prefix = "thumbnail_"; 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 ThumbnailTools setSize(int size){
this.width = size;
this.height = size;
return this;
} public ThumbnailTools setSize(int width, int height){
this.width = width;
this.height = height;
return this;
} public String getInPath() {
return inPath;
} public void setInPath(String inPath) {
this.inPath = inPath;
} public String getOutPath() {
return outPath;
} public void setOutPath(String outPath) {
this.outPath = outPath;
} public boolean isProportion() {
return proportion;
} public void setProportion(boolean proportion) {
this.proportion = proportion;
} public ThumbnailTools(String path){
this.inPath = path;
this.outPath = path;
} public ThumbnailTools(String inPath, String outPath){
this.inPath = inPath;
this.outPath = outPath;
} /**
* 生成缩略图
* @param fileName 文件名
* @return boolean
*/
public boolean generate(String fileName) throws Exception{
this.generate(fileName, null);
return Boolean.TRUE;
} /**
* 生成缩略图
* @param fileName 文件名
* @param outFileName 输出文件名
* @return boolean
*/
public boolean generate(String fileName, String outFileName) throws Exception{
File file = new File(inPath+fileName);
this.inFileName = fileName;
this.outFileName = null == outFileName ? prefix+inFileName : outFileName;
this.execute(new FileInputStream(file));
return Boolean.TRUE;
} public boolean generate(InputStream inputStream, String outPath) throws Exception{
this.execute(inputStream); return Boolean.TRUE;
} private void execute(InputStream inputStream) throws Exception {
this.fileSize = inputStream.available();
BufferedImage oldImage = ImageIO.read(inputStream);
if (oldImage.getWidth() == -1) {
System.out.println("Input image cant't read or format error.");
return;
} int newWidth;
int newHeight;
// 是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) oldImage.getWidth()) / (double) width;
double rate2 = ((double) oldImage.getHeight()) / (double) height;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) oldImage.getWidth()) / rate);
newHeight = (int) (((double) oldImage.getHeight()) / rate);
} else {
newWidth = width; // 输出的图片宽度
newHeight = height; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB); // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
tag.getGraphics().drawImage(oldImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
String newFilePath = outPath+outFileName;
File newFile = new File(newFilePath);
FileOutputStream out = new FileOutputStream(newFile);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
inputStream.close();
out.close(); System.out.println(newFilePath+" ok, size: "+(fileSize/1024)+"kb to "+(newFile.length()/1024)+"kb");
} public static void main(String[] args) {
try {
new ThumbnailTools("D:/").setSize(300, 200).generate("1.jpg", "2.jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
}

大家在运行的时候或许会报错,因为该程序需要java两个jar包的支持

在Eclipse中处理图片,需要引入两个包:

import com.sun.image.codec.jpeg.JPEGCodec;


import com.sun.image.codec.jpeg.JPEGImageEncoder;


报错:


Access
restriction: The type JPEGImageEncoder is not accessible due to
restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar

此时解决办法:
Eclipse默认把这些受访问限制的API设成了ERROR。只要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的Deprecated
and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。

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

  1. JAVA生成图片缩略图、JAVA截取图片局部内容

    package com.ares.image.test; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; ...

  2. java图片裁剪和java生成缩略图

    一.缩略图 在浏览相冊的时候.可能须要生成相应的缩略图. 直接上代码: public class ImageUtil { private Logger log = LoggerFactory.getL ...

  3. PHP一般情况下生成的缩略图都比较不理想

    PHP用GD库生成高质量的缩略图片,PHP一般情况下生成的缩略图都比较不理想.今天试用PHP,GD库来生成缩略图.虽然并不100%完美.可是也应该可以满足缩略图的要求了.<?php $FILEN ...

  4. PHP原生写的生成图片缩略图类

    PHP原生写的生成图片缩略图类,本文以京东商品图片为例,分别生成三种不同尺寸的图片.调用方法很简单只要传参数高度和宽度,及新图片的名称. 引入缩略图类 include_once 'ImageResiz ...

  5. java 生成二维码、可带LOGO、可去白边

      1.准备工作 所需jar包: JDK 1.6: commons-codec-1.11.jar core-2.2.jar javase-2.2.jar JDK 1.7: commons-codec- ...

  6. java 生成二维码后叠加LOGO并转换成base64

      1.代码 见文末推荐 2.测试 测试1:生成base64码 public static void main(String[] args) throws Exception { String dat ...

  7. springboot搭建项目,实现Java生成随机图片验证码。

    这篇文章主要介绍了如何通过Java如何生成验证码并验证.验证码的作用我想必大家都知道,话不多说开始实施! 首先创建一个springboot项目以下是项目结构,内有utli工具类.存放生成图片验证码方法 ...

  8. c#.net 生成清晰缩略图

    1 public void imgsize() 2 { 3 //本例中假定了两个变量: 4 5 String src = "c:/myImages/a.jpg"; //源图像文件的 ...

  9. Java生成和操作Excel文件(转载)

    Java生成和操作Excel文件   JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该A ...

随机推荐

  1. singleton(单件)-对象创建型模式

    1.意图 保证一个类仅有一个实例,并提供一个访问它的全局访问点. 2.动机 对一些类来说,只有一个实例是很重要的.让类自身负责保存它唯一的实例,这个类可以保证没有其他实例可以被创建(通过截取创建新对象 ...

  2. reason: '-[__NSCFNumber rangeOfCharacterFromSet:]: unrecognized selector sent to instance

    类型的不匹配,把类型转化对应的数据类型,例: model.price 是模型数据,其值为1550: cell.label.text = [NSString stringWithFormat:@&quo ...

  3. componentsSeparatedByString,componentsJoinedByString,componentsSeparatedByCharactersInSet

    将string字符串转换为array数组 NSArray  *array = [Str componentsSeparatedByString:@","]; ==反向方法 将arr ...

  4. linux或者windows下的文件拷贝

    #  上代码 #!/usr/bin/env python # -*- coding:utf-8 -*- import os import shutil import tarfile base_dir ...

  5. JavaScript密码复杂度

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...

  6. JProfiler使用入门(一)——准备工作

      JProfiler是一个全功能的Java剖析工具(profiler),主要用于检查和跟踪系统(限于Java开发的)的性能. JProfiler可以通过时时的监控系统的内存使用情况,随时监视垃圾回收 ...

  7. 咏南IOCP REST中间件

    咏南IOCP REST中间件 让DELPHI7也能编写REST服务. 使用IOCP通信+UNIDAC数据库引擎. 客户端跨开发语言调用.

  8. POJ 3686 The Windy's 最小费用最大流

    每个工厂拆成N个工厂,费用分别为1~N倍原费用. //#pragma comment(linker, "/STACK:1024000000,1024000000") #includ ...

  9. Excel表格常用的函数,留着备用

    1. vlookup(lookup_value, table_array, col_index_num, boolean) -- 查找匹配函数 lookup_value: 你要去匹配的值 table_ ...

  10. treeMap and treeSet

    TreeSet:如果要对对象进行排序,对象类要实现Comparable接口! TreeMap:如果要对对象进行排序,对象类要实现Comparable接口! 下面是我自己写的小程序主要传输对象 publ ...