JAVA生成图片缩略图、JAVA截取图片局部内容
package com.ares.image.test; import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays; import javax.imageio.ImageIO; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.ares.slf4j.test.Slf4jUtil; /**
* <p>Title: ImageUtil </p>
* <p>Description: 使用JDK原生态类生成图片缩略图和裁剪图片 </p>
* <p>Email: icerainsoft@hotmail.com </p>
* @author Ares
* @date 2014年10月28日 上午10:24:26
*/
public class ImageUtil { static {
Slf4jUtil.buildSlf4jUtil().loadSlf4j();
}
private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_PREVFIX = "thumb_";
private static Boolean DEFAULT_FORCE = false; /**
* <p>Title: thumbnailImage</p>
* <p>Description: 根据图片路径生成缩略图 </p>
* @param imagePath 原图片路径
* @param w 缩略图宽
* @param h 缩略图高
* @param prevfix 生成缩略图的前缀
* @param force 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
*/
public void thumbnailImage(File imgFile, int w, int h, String prevfix, boolean force){
if(imgFile.exists()){
try {
// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
String types = Arrays.toString(ImageIO.getReaderFormatNames());
String suffix = null;
// 获取图片后缀
if(imgFile.getName().indexOf(".") > -1) {
suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
}// 类型和图片后缀全部小写,然后判断后缀是否合法
if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
return ;
}
log.debug("target image's size, width:{}, height:{}.",w,h);
Image img = ImageIO.read(imgFile);
if(!force){
// 根据原图与要求的缩略图比例,找到最合适的缩略图比例
int width = img.getWidth(null);
int height = img.getHeight(null);
if((width*1.0)/w < (height*1.0)/h){
if(width > w){
h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
log.debug("change image's height, width:{}, height:{}.",w,h);
}
} else {
if(height > h){
w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
log.debug("change image's width, width:{}, height:{}.",w,h);
}
}
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
g.dispose();
String p = imgFile.getPath();
// 将图片保存在原目录并加上前缀
ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
} catch (IOException e) {
log.error("generate thumbnail image failed.",e);
}
}else{
log.warn("the image is not exist.");
}
} public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){
File imgFile = new File(imagePath);
thumbnailImage(imgFile, w, h, prevfix, force);
} public void thumbnailImage(String imagePath, int w, int h, boolean force){
thumbnailImage(imagePath, w, h, DEFAULT_PREVFIX, force);
} public void thumbnailImage(String imagePath, int w, int h){
thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
} public static void main(String[] args) {
new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 100, 150);
} }
效果:(原图是电脑"图片"文件夹下的郁金香图片,大小1024*768,生成的图片为200*150大小,保持4:3的比例)

package com.ares.image.test; import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays; import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.ares.slf4j.test.Slf4jUtil; /**
* <p>Title: ImageUtil </p>
* <p>Description: </p>
* <p>Email: icerainsoft@hotmail.com </p>
* @author Ares
* @date 2014年10月28日 上午10:24:26
*/
public class ImageUtil { static {
Slf4jUtil.buildSlf4jUtil().loadSlf4j();
}
private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_THUMB_PREVFIX = "thumb_";
private static String DEFAULT_CUT_PREVFIX = "cut_";
private static Boolean DEFAULT_FORCE = false; /**
* <p>Title: cutImage</p>
* <p>Description: 根据原图与裁切size截取局部图片</p>
* @param srcImg 源图片
* @param output 图片输出流
* @param rect 需要截取部分的坐标和大小
*/
public void cutImage(File srcImg, OutputStream output, java.awt.Rectangle rect){
if(srcImg.exists()){
java.io.FileInputStream fis = null;
ImageInputStream iis = null;
try {
fis = new FileInputStream(srcImg);
// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
String suffix = null;
// 获取图片后缀
if(srcImg.getName().indexOf(".") > -1) {
suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
}// 类型和图片后缀全部小写,然后判断后缀是否合法
if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
return ;
}
// 将FileInputStream 转换为ImageInputStream
iis = ImageIO.createImageInputStream(fis);
// 根据图片类型获取该种类型的ImageReader
ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
reader.setInput(iis,true);
ImageReadParam param = reader.getDefaultReadParam();
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi, suffix, output);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fis != null) fis.close();
if(iis != null) iis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
log.warn("the src image is not exist.");
}
} public void cutImage(File srcImg, OutputStream output, int x, int y, int width, int height){
cutImage(srcImg, output, new java.awt.Rectangle(x, y, width, height));
} public void cutImage(File srcImg, String destImgPath, java.awt.Rectangle rect){
File destImg = new File(destImgPath);
if(destImg.exists()){
String p = destImg.getPath();
try {
if(!destImg.isDirectory()) p = destImg.getParent();
if(!p.endsWith(File.separator)) p = p + File.separator;
cutImage(srcImg, new java.io.FileOutputStream(p + DEFAULT_CUT_PREVFIX + "_" + new java.util.Date().getTime() + "_" + srcImg.getName()), rect);
} catch (FileNotFoundException e) {
log.warn("the dest image is not exist.");
}
}else log.warn("the dest image folder is not exist.");
} public void cutImage(File srcImg, String destImg, int x, int y, int width, int height){
cutImage(srcImg, destImg, new java.awt.Rectangle(x, y, width, height));
} public void cutImage(String srcImg, String destImg, int x, int y, int width, int height){
cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height));
}
/**
* <p>Title: thumbnailImage</p>
* <p>Description: 根据图片路径生成缩略图 </p>
* @param imagePath 原图片路径
* @param w 缩略图宽
* @param h 缩略图高
* @param prevfix 生成缩略图的前缀
* @param force 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
*/
public void thumbnailImage(File srcImg, OutputStream output, int w, int h, String prevfix, boolean force){
if(srcImg.exists()){
try {
// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
String suffix = null;
// 获取图片后缀
if(srcImg.getName().indexOf(".") > -1) {
suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
}// 类型和图片后缀全部小写,然后判断后缀是否合法
if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
return ;
}
log.debug("target image's size, width:{}, height:{}.",w,h);
Image img = ImageIO.read(srcImg);
// 根据原图与要求的缩略图比例,找到最合适的缩略图比例
if(!force){
int width = img.getWidth(null);
int height = img.getHeight(null);
if((width*1.0)/w < (height*1.0)/h){
if(width > w){
h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
log.debug("change image's height, width:{}, height:{}.",w,h);
}
} else {
if(height > h){
w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
log.debug("change image's width, width:{}, height:{}.",w,h);
}
}
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
g.dispose();
// 将图片保存在原目录并加上前缀
ImageIO.write(bi, suffix, output);
output.close();
} catch (IOException e) {
log.error("generate thumbnail image failed.",e);
}
}else{
log.warn("the src image is not exist.");
}
}
public void thumbnailImage(File srcImg, int w, int h, String prevfix, boolean force){
String p = srcImg.getAbsolutePath();
try {
if(!srcImg.isDirectory()) p = srcImg.getParent();
if(!p.endsWith(File.separator)) p = p + File.separator;
thumbnailImage(srcImg, new java.io.FileOutputStream(p + prevfix +srcImg.getName()), w, h, prevfix, force);
} catch (FileNotFoundException e) {
log.error("the dest image is not exist.",e);
}
} public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){
File srcImg = new File(imagePath);
thumbnailImage(srcImg, w, h, prevfix, force);
} public void thumbnailImage(String imagePath, int w, int h, boolean force){
thumbnailImage(imagePath, w, h, DEFAULT_THUMB_PREVFIX, DEFAULT_FORCE);
} public void thumbnailImage(String imagePath, int w, int h){
thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
} public static void main(String[] args) {
new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 150, 100);
new ImageUtil().cutImage("imgs/Tulips.jpg","imgs", 250, 70, 300, 400);
} }
效果如下:(使用在上传图片时取缩略图和截图的地方,例如,头像截取并缩略)

转载 http://www.cnblogs.com/icerainsoft/p/4056393.html
JAVA生成图片缩略图、JAVA截取图片局部内容的更多相关文章
- java图片裁剪和java生成缩略图
一.缩略图 在浏览相冊的时候.可能须要生成相应的缩略图. 直接上代码: public class ImageUtil { private Logger log = LoggerFactory.getL ...
- java分别通过httpclient和HttpURLConnection获取图片验证码内容
前面的文章,介绍了如何通过selenium+Tesseract-OCR来识别图片验证码,如果用接口来访问的话,再用selenium就闲的笨重,下面就介绍一下分别通过httpclient和HttpURL ...
- Java截取图片的一部分并保存为40*40的图片
@Test public void testImag() { try { String path = "E:/flower2.jpg"; int x = 11, y = 20, c ...
- Java实现用汉明距离进行图片相似度检测的
Google.Baidu 等搜索引擎相继推出了以图搜图的功能,测试了下效果还不错~ 那这种技术的原理是什么呢?计算机怎么知道两张图片相似呢? 根据Neal Krawetz博士的解释,原理非常简单易懂. ...
- Atitit java 二维码识别 图片识别
Atitit java 二维码识别 图片识别 1.1. 解码11.2. 首先,我们先说一下二维码一共有40个尺寸.官方叫版本Version.11.3. 二维码的样例:21.4. 定位图案21.5. 数 ...
- java生成二维码图片
1.POM文件引入 <dependency> <groupId>com.google.zxing</groupId> <artifactId>core& ...
- java Html2Image 实现html转图片功能
//java Html2Image 实现html转图片功能 // html2image HtmlImageGenerator imageGenerator = new HtmlImageGenera ...
- java实现随机验证码的图片
链接地址:http://blog.sina.com.cn/s/blog_407a68fc010006qo.html 1.一共需要2个常用java文件(RandomCode.java和RandomCod ...
- 【转】Java生成图片验证码
原文转自:http://blog.csdn.net/ruixue0117/article/details/22829557 看了挺多图片验证码的代码,感觉没什么长的好看点的,就自己动手写了个,写完发现 ...
随机推荐
- VC++6.0编译器标记的那些内存值
栈内存初始值 0xcccccccc 和-858993460. 二者是一样的, 一个是16进制, 另一个是10进制
- 词频junit测试
package search; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; impor ...
- 从客户端中检测到有潜在危险的 request.form值[解决方法]
当页面编辑或运行提交时,出现“从客户端中检测到有潜在危险的request.form值”问题,该怎么办呢?如下图所示: 下面博主汇总出现这种错误的几种解决方法:问题原因:由于在asp.net中,Requ ...
- 大量查询SQL语句 实例
1.查看表结构语句:DESC 表名 2.查询所有列:select * from 表名 3.查询指定列:select 字段名 form 表名 4.查询指定行:SELECT * ...
- Matlab图像处理函数:regionprops
本篇文章为转载,仅为方便学术讨论所用,不用于商业用途.由于时间较久,原作者以及原始链接暂时无法找到,如有侵权以及其他任何事宜欢迎跟我联系,如有侵扰,在此提前表示歉意.----------------- ...
- Codeforces Round #361 (Div. 2) C D
C 给出一个m 此时有 四个数 分别为x k*x k*k*x k*k*k*x k大于1 x大于等于1 要求求出来一个最小的值n 使其满足 这四个数中的最大值小于n 这四个数可能的组数为m 可以看出这四 ...
- angular 路由去除#号
1. 路由启动 $locationProvider.html5Mode(true); 通过pushstatex修改url app.js define([ 'angular', & ...
- ORA-01436: 用户数据中的CONNECT BY 循环
起始地 目的地 距离(公里)A B 1000A C 1100A ...
- Git branch 和 Git checkout常见用法
git branch 和 git checkout经常在一起使用,所以在此将它们合在一起 1.Git branch 一般用于分支的操作,比如创建分支,查看分支等等, 1.1 git branch 不带 ...
- 对于字符串拼接,string.format、stringbuilder、+=
sring拼接经常会用到,拼接时候使用的方法,每个人的又不一样,有的是不知道哪个效率高,也有一些是为了方便不差那么一点时间! 今天百度查了查他们的区别! += 是效率最低的一个,尽量避免使用,当然,不 ...