java图片缩放工具类,一个JAVA图形缩放处置工具类
一个JAVA图形缩放处理工具类
调用的例子
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class T {
public static void main(String[] args) throws Exception, IOException {
ImageIO.write(ImageUtils.resizeImage("d:/www.java2000.net.gif", ImageUtils.IMAGE_GIF, 30, 20),
"JPEG", new FileOutputStream("d:/test.jpg"));
}
}
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
public class ImageUtils {
public static final int IMAGE_UNKNOWN = -1;
public static final int IMAGE_JPEG = 0;
public static final int IMAGE_PNG = 1;
public static final int IMAGE_GIF = 2;
/**
* Resizes an image
*
* @param imgName
* The image name to resize. Must be the complet path to the file
* @param type
* int
* @param maxWidth
* The image's max width
* @param maxHeight
* The image's max height
* @return A resized BufferedImage
*/
public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight) {
try {
return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Resizes an image.
*
* @param image
* The image to resize
* @param maxWidth
* The image's max width
* @param maxHeight
* The image's max height
* @return A resized BufferedImage
* @param type
* int
*/
public static BufferedImage resizeImage(BufferedImage image, int type, int maxWidth, int maxHeight) {
Dimension largestDimension = new Dimension(maxWidth, maxHeight);
// Original size
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
float aspectRatio = (float) imageWidth / imageHeight;
if (imageWidth > maxWidth || imageHeight > maxHeight) {
if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio);
} else {
largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio);
}
imageWidth = largestDimension.width;
imageHeight = largestDimension.height;
}
return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight);
}
/**
* Saves an image to the disk.
*
* @param image
* The image to save
* @param toFileName
* The filename to use
* @param type
* The image type. Use ImageUtils.IMAGE_JPEG
to save as
* JPEG images, or ImageUtils.IMAGE_PNG
to save as PNG.
* @return false
if no appropriate writer is found
*/
public static boolean saveImage(BufferedImage image, String toFileName, int type) {
try {
return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Compress and save an image to the disk. Currently this method only supports
* JPEG images.
*
* @param image
* The image to save
* @param toFileName
* The filename to use
* @param type
* The image type. Use ImageUtils.IMAGE_JPEG
to save as
* JPEG images, or ImageUtils.IMAGE_PNG
to save as PNG.
*/
public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
try {
if (type == IMAGE_PNG) {
throw new UnsupportedOperationException("PNG compression not implemented");
}
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer;
writer = (ImageWriter) iter.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
writer.setOutput(ios);
ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(0.7F);
writer.write(null, new IIOImage(image, null, null), iwparam);
ios.flush();
writer.dispose();
ios.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Creates a BufferedImage
from an Image
. This
* method can function on a completely headless system. This especially
* includes Linux and Unix systems that do not have the X11 libraries
* installed, which are required for the AWT subsystem to operate. This method
* uses nearest neighbor approximation, so it's quite fast. Unfortunately, the
* result is nowhere near as nice looking as the
* createHeadlessSmoothBufferedImage method.
*
* @param image
* The image to convert
* @param w
* The desired image width
* @param h
* The desired image height
* @return The converted image
* @param type
* int
*/
public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width,
int height) {
if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
type = BufferedImage.TYPE_INT_ARGB;
} else {
type = BufferedImage.TYPE_INT_RGB;
}
BufferedImage bi = new BufferedImage(width, height, type);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
}
}
return bi;
}
/**
* Creates a BufferedImage
from an Image
. This
* method can function on a completely headless system. This especially
* includes Linux and Unix systems that do not have the X11 libraries
* installed, which are required for the AWT subsystem to operate. The
* resulting image will be smoothly scaled using bilinear filtering.
*
* @param source
* The image to convert
* @param w
* The desired image width
* @param h
* The desired image height
* @return The converted image
* @param type
* int
*/
public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type,
int width, int height) {
if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
type = BufferedImage.TYPE_INT_ARGB;
} else {
type = BufferedImage.TYPE_INT_RGB;
}
BufferedImage dest = new BufferedImage(width, height, type);
int sourcex;
int sourcey;
double scalex = (double) width / source.getWidth();
double scaley = (double) height / source.getHeight();
int x1;
int y1;
double xdiff;
double ydiff;
int rgb;
int rgb1;
int rgb2;
for (int y = 0; y < height; y++) {
sourcey = y * source.getHeight() / dest.getHeight();
ydiff = scale(y, scaley) - sourcey;
for (int x = 0; x < width; x++) {
sourcex = x * source.getWidth() / dest.getWidth();
xdiff = scale(x, scalex) - sourcex;
x1 = Math.min(source.getWidth() - 1, sourcex + 1);
y1 = Math.min(source.getHeight() - 1, sourcey + 1);
rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey),
xdiff);
rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);
rgb = getRGBInterpolation(rgb1, rgb2, ydiff);
dest.setRGB(x, y, rgb);
}
}
return dest;
}
private static double scale(int point, double scale) {
return point / scale;
}
private static int getRGBInterpolation(int value1, int value2, double distance) {
int alpha1 = (value1 & 0xFF000000) >>> 24;
int red1 = (value1 & 0x00FF0000) >> 16;
int green1 = (value1 & 0x0000FF00) >> 8;
int blue1 = (value1 & 0x000000FF);
int alpha2 = (value2 & 0xFF000000) >>> 24;
int red2 = (value2 & 0x00FF0000) >> 16;
int green2 = (value2 & 0x0000FF00) >> 8;
int blue2 = (value2 & 0x000000FF);
int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) << 24)
| ((int) (red1 * (1.0 - distance) + red2 * distance) << 16)
| ((int) (green1 * (1.0 - distance) + green2 * distance) << 8)
| (int) (blue1 * (1.0 - distance) + blue2 * distance);
return rgb;
}
/**
* Determines if the image has transparent pixels.
*
* @param image
* The image to check for transparent pixel.s
* @return true
of false
, according to the result
*/
public static boolean hasAlpha(Image image) {
try {
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
pg.grabPixels();
return pg.getColorModel().hasAlpha();
} catch (InterruptedException e) {
return false;
}
}
}
java图片缩放工具类,一个JAVA图形缩放处置工具类相关推荐
- java 图形校验_java图形验证码生成工具类 web页面校验验证码
java图形验证码生成工具类 web页面校验验证码 发布于 2020-7-14| 复制链接 摘记: 最近做验证码,参考网上案例,发现有不少问题,特意进行了修改和完善.验证码生成器: ```java i ...
- java图形验证码生成工具类
转载自 java图形验证码生成工具类 生成验证码效果 ValidateCode.java 验证码生成类 package cn.dsna.util.images; import java ...
- (一)初识java ---我的第一个java程序
初识java ---我的第一个java程序 课程目录 l 準備 l 開発環境的準備 l 環境変数Path設定 l 第一个程序 目标 « 实现自己的HelloWorld并运行看到结果 一.準備 ...
- java 中间容器 表格_【JAVA SE基础篇】45.迭代器、Collections工具类以及使用容器存储表格...
本文将要为您介绍的是[JAVA SE基础篇]45.迭代器.Collections工具类以及使用容器存储表格,具体完成步骤: 1.迭代器 迭代器为我们提供了统一遍历容器(List/Map/Set)的方式 ...
- Java通用工具类之按对象属性排序工具类
本工具类为按对象属性排序工具类,实现的功能: 1.按对象的一个属性和多个属性进行排序. 2.按对象属性正序和倒序排列. 3.完美支持int等基础类和Integer等包装类. 4.完美支持属性为实现了C ...
- java 视频转码工具类_JavaCV入门指南:FrameConverter转换工具类及CanvasFrame图像预览工具类(javaCV教程完结篇)...
JavaCV入门指南:FrameConverter转换工具类及CanvasFrame图像预览工具类(javaCV教程完结篇) 前言 再此章之前,我们已经详细介绍和剖析了javacv的结构和ffmpeg ...
- 「Java工具类」Apache的StringEscapeUtils转义工具类
介绍语 本号主要是Java常用关键技术点,通用工具类的分享:以及springboot+springcloud+Mybatisplus+druid+mysql+redis+swagger+maven+d ...
- Java操作大数据量Excel导入导出万能工具类(完整版)
Java操作大数据量Excel导入导出万能工具类(完整版) 转载自:https://blog.csdn.net/JavaWebRookie/article/details/80843653 更新日志: ...
- JAVA获取N个工作日后的时间的工具类、考虑上班时间、时区
DayWorkTime代表工作时间描述类 HolidayUtils是计算时间的工具类,addSecondByWorkDay用于计算时间加上指定秒后的工作时间,会自动跳过周末.节假日等.其中holida ...
最新文章
- 根据CPU核数合理设置线程池大小
- 用电脑发短信_重磅!一个软件实现电脑上接打手机电话、收发短信、传文件、屏幕镜像!...
- 互联网巨头们的「中台战事」
- 未来一瞥:机器人码农
- linux清理swap内容,Linux如何清理swap.buffer及cache等缓存
- struts2重定向
- Business Partner Relationship Category in CRM and C4C
- c语言程序中的if-else语句,C语言if else语句
- 第一个工程 HttpLoader
- java 占位符_Java重要知识点
- php mysql 组件_Ubuntu20.04安装apache、mysql、php、phpmyadmin、wordpress(一)
- 如何给软件开发项目估价?
- 【JSP】EL表达式和JSTL
- protel常用元件封装大全
- jmail 发送html,jmail发送html格式的邮件
- Windows下的conda换源和pip换源
- java工具类书写规范
- 高质量蓝牙耳机推荐,2023年热销火爆的蓝牙耳机推荐
- Revisiting The Lows
- 基于FPGA的数字电子琴——数电小系统设计【数字电子技术】(使用Vivado中的verilog语言)含piano代码文件(全)
热门文章
- 3.3 超参数训练实战:Pandas vs. Caviar-深度学习第二课《改善深层神经网络》-Stanford吴恩达教授
- stm32f030cc 替换 stm32f030c8 后程序下载失败问题
- 【树莓派】树莓派SD卡系统镜像系统备份方法
- FPGA篇(十二)仿真中 `timesclae的用法
- Class.getResourceAsStream和ClassLoader.getResourceAsStream方法
- [PHP] 算法-合并两个有序链表为一个有序链表的PHP实现
- 【原创】纯干货,Spring-data-jpa详解,全方位介绍。(转)
- 老男孩Linux运维第41期20171016第六周学习重点课堂记录
- hadoop环境搭建之伪分布集群环境搭建(单节点)
- SQL SERVER 数据库 怎么从一个服务器一个表中把数据插入到另一个服务器中的一个表内(纯复制)...