`

Java 缩放图片工具类,创建缩略图、伸缩图片比例

    博客分类:
  • Java
 
阅读更多
http://my.oschina.net/backtract/blog/403828
支持将Image的宽度、高度缩放到指定width、height,并保存在指定目录

通过目标对象的大小和标准(指定)大小计算出图片缩小的比例

可以设置图片缩放质量,并且可以根据指定的宽高缩放图片

package com.hoo.util;
  
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
  
/**
 * <b>function:</b> 缩放图片工具类,创建缩略图、伸缩图片比例
 * @author hoojo
 * @createDate 2012-2-3 上午10:08:47
 * @file ScaleImageUtils.java
 * @package com.hoo.util
 * @blog http://blog.csdn.net/IBM_hoojo
 * http://hoojo.cnblogs.com
 * @email hoojo_@126.com
 * @version 1.0
 */
public abstract class ScaleImageUtils {
  
    private static final float DEFAULT_SCALE_QUALITY = 1f;
    private static final String DEFAULT_IMAGE_FORMAT = ".jpg"; // 图像文件的格式 
    private static final String DEFAULT_FILE_PATH = "C:/temp-";
     
    /**
     * <b>function:</b> 设置图片压缩质量枚举类;
     * Some guidelines: 0.75 high quality、0.5  medium quality、0.25 low quality
     * @author hoojo
     * @createDate 2012-2-7 上午11:31:45
     * @file ScaleImageUtils.java
     * @package com.hoo.util
     * @project JQueryMobile
     * @blog http://blog.csdn.net/IBM_hoojo
     * @email hoojo_@126.com
     * @version 1.0
     */
    public enum ImageQuality {
        max(1.0f), high(0.75f), medium(0.5f), low(0.25f);
         
        private Float quality;
        public Float getQuality() {
            return this.quality;
        }
        ImageQuality(Float quality) {
            this.quality = quality;
        }
    }
     
    private static Image image;
     
    /**
     * <b>function:</b> 通过目标对象的大小和标准(指定)大小计算出图片缩小的比例
     * @author hoojo
     * @createDate 2012-2-6 下午04:41:48
     * @param targetWidth 目标的宽度
     * @param targetHeight 目标的高度
     * @param standardWidth 标准(指定)宽度
     * @param standardHeight 标准(指定)高度
     * @return 最小的合适比例
     */
    public static double getScaling(double targetWidth, double targetHeight, double standardWidth, double standardHeight) {
        double widthScaling = 0d;
        double heightScaling = 0d;
        if (targetWidth > standardWidth) {
            widthScaling = standardWidth / (targetWidth * 1.00d);
        } else {
            widthScaling = 1d;
        }
        if (targetHeight > standardHeight) {
            heightScaling = standardHeight / (targetHeight * 1.00d);
        } else {
            heightScaling = 1d;
        }
        return Math.min(widthScaling, heightScaling);
    }
     
    /**
     * <b>function:</b> 将Image的宽度、高度缩放到指定width、height,并保存在savePath目录
     * @author hoojo
     * @createDate 2012-2-6 下午04:54:35
     * @param width 缩放的宽度
     * @param height 缩放的高度
     * @param savePath 保存目录
     * @param targetImage 即将缩放的目标图片
     * @return 图片保存路径、名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, Image targetImage) throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
         
        if (savePath == null || "".equals(savePath)) {
            savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
        }
         
        FileOutputStream fos = new FileOutputStream(new File(savePath));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        encoder.encode(image);
  
        image.flush();
        fos.flush();
        fos.close();
         
        return savePath;
    }
     
    /**
     * <b>function:</b> 可以设置图片缩放质量,并且可以根据指定的宽高缩放图片
     * @author hoojo
     * @createDate 2012-2-7 上午11:01:27
     * @param width 缩放的宽度
     * @param height 缩放的高度
     * @param quality 图片压缩质量,最大值是1; 使用枚举值:{@link ImageQuality}
     *             Some guidelines: 0.75 high quality、0.5  medium quality、0.25 low quality
     * @param savePath 保存目录
     * @param targetImage 即将缩放的目标图片
     * @return 图片保存路径、名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, Float quality, String savePath, Image targetImage) throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
         
        if (savePath == null || "".equals(savePath)) {
            savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
        }
         
        FileOutputStream fos = new FileOutputStream(new File(savePath));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
         
        JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image); 
        if (quality == null || quality <= 0) {
            quality = DEFAULT_SCALE_QUALITY;
        }
        /** 设置图片压缩质量 */  
        encodeParam.setQuality(quality, true);  
        encoder.encode(image, encodeParam);  
  
        image.flush();
        fos.flush();
        fos.close();
         
        return savePath;
    }
     
    /**
     * <b>function:</b> 通过指定大小和图片的大小,计算出图片缩小的合适大小
     * @author hoojo
     * @createDate 2012-2-6 下午05:53:10
     * @param width 指定的宽度
     * @param height 指定的高度
     * @param image 图片文件
     * @return 返回宽度、高度的int数组
     */
    public static int[] getSize(int width, int height, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        double scaling = getScaling(targetWidth, targetHeight, width, height);
        long standardWidth = Math.round(targetWidth * scaling);
        long standardHeight = Math.round(targetHeight * scaling);
        return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
    }
     
    /**
     * <b>function:</b> 通过指定的比例和图片对象,返回一个放大或缩小的宽度、高度
     * @author hoojo
     * @createDate 2012-2-7 上午10:27:59
     * @param scale 缩放比例
     * @param image 图片对象
     * @return 返回宽度、高度
     */
    public static int[] getSize(float scale, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long standardWidth = Math.round(targetWidth * scale);
        long standardHeight = Math.round(targetHeight * scale);
        return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
    }
     
    public static int[] getSize(int width, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long height = Math.round((targetHeight * width) / (targetWidth * 1.00f));
        return new int[] { width, Integer.parseInt(String.valueOf(height)) };
    }
     
    public static int[] getSizeByHeight(int height, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long width = Math.round((targetWidth * height) / (targetHeight * 1.00f));
        return new int[] { Integer.parseInt(String.valueOf(width)), height };
    }
     
    /**
     * 
     * <b>function:</b> 将指定的targetFile图片文件的宽度、高度大于指定width、height的图片缩小,并保存在savePath目录
     * @author hoojo
     * @createDate 2012-2-6 下午04:57:02
     * @param width 缩小的宽度
     * @param height 缩小的高度
     * @param savePath 保存目录
     * @param targetImage 改变的目标图片
     * @return 图片保存路径、名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(width, height, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * 
     * <b>function:</b> 将指定的targetURL网络图片文件的宽度、高度大于指定width、height的图片缩小,并保存在savePath目录
     * @author hoojo
     * @createDate 2012-2-6 下午04:57:07
     * @param width 缩小的宽度
     * @param height 缩小的高度
     * @param savePath 保存目录
     * @param targetImage 改变的目标图片
     * @return 图片保存路径、名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(width, height, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b> 将一个本地的图片文件按照指定的比例进行缩放
     * @author hoojo
     * @createDate 2012-2-7 上午10:29:18
     * @param scale 缩放比例
     * @param savePath 保存文件路径、名称
     * @param targetFile 本地图片文件
     * @return 新的文件名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(float scale, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(scale, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b> 将一个网络图片文件按照指定的比例进行缩放
     * @author hoojo
     * @createDate 2012-2-7 上午10:30:56
     * @param scale 缩放比例
     * @param savePath 保存文件路径、名称
     * @param targetFile 本地图片文件
     * @return 新的文件名称
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(float scale, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(scale, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b> 按照固定宽度进行等比缩放本地图片
     * @author hoojo
     * @createDate 2012-2-7 上午10:49:56
     * @param width 固定宽度
     * @param savePath 保存路径、名称
     * @param targetFile 本地目标文件
     * @return 返回保存路径
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(width, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b> 按照固定宽度进行等比缩放网络图片
     * @author hoojo
     * @createDate 2012-2-7 上午10:50:52
     * @param width 固定宽度
     * @param savePath 保存路径、名称
     * @param targetFile 本地目标文件
     * @return 返回保存路径
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(width, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * 
     * <b>function:</b> 按照固定高度进行等比缩放本地图片
     * @author hoojo
     * @createDate 2012-2-7 上午10:51:17
     * @param height 固定高度
     * @param savePath 保存路径、名称
     * @param targetFile 本地目标文件
     * @return 返回保存路径
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resizeByHeight(int height, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSizeByHeight(height, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b> 按照固定高度进行等比缩放网络图片
     * @author hoojo
     * @createDate 2012-2-7 上午10:52:23
     * @param height 固定高度
     * @param savePath 保存路径、名称
     * @param targetFile 本地目标文件
     * @return 返回保存路径
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resizeByHeight(int height, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSizeByHeight(height, image);
        return resize(size[0], size[1], savePath, image);
    }
     
    /**
     * <b>function:</b>
     * @author hoojo
     * @createDate 2012-2-3 上午10:08:47
     * @param args
     * @throws IOException 
     * @throws MalformedURLException 
     * @throws ImageFormatException 
     */
    public static void main(String[] args) throws ImageFormatException, MalformedURLException, IOException {
         
        System.out.println(ScaleImageUtils.resize(140, 140, null, new URL("http://www.open-open.com/lib/images/logo.jpg")));
        ScaleImageUtils.resize(100, 100, ImageQuality.high.getQuality(), null, ImageIO.read(new URL("http://www.open-open.com/lib/images/logo.jpg")));
    }
}
分享到:
评论

相关推荐

    php缩略图php图片缩放php图片压缩

    总的来说,PHP的GD库为我们提供了一套强大的工具,可以方便地进行图像处理,包括创建缩略图、缩放图片以及压缩图片。通过熟练运用这些功能,我们可以提升网站或应用的用户体验,同时优化服务器资源的使用。

    图片按比例缩放

    这些工具通常提供“自由变换”功能,允许用户输入特定的缩放比例,或者通过拖动角落的控制点来等比例调整图片大小。 在编程领域,我们也可以利用各种编程语言实现图片的按比例缩放。例如,Python中的PIL(Pillow)...

    java图片处理工具类ImgUtils.java

    实现功能: 叠加图片;图片压缩(支持MultipartFile),添加文本–可根据textWidth参数自动换行,支持行间距、字间距设置;...图片高质量缩放;图片png格式缩放;图片克隆副本;读取图片对象;图片输出 ……

    基于Springmvc的上传图片并生成缩略图

    在本文中,我们将深入探讨如何基于Springmvc实现图片上传及生成缩略图的功能。Springmvc是Spring框架的一个重要模块,用于构建MVC模式的Web应用,它提供了强大的数据绑定、模型映射、视图渲染等功能,是Java开发中的...

    javapng透明图片缩略

    在Java编程中,生成PNG透明图片的缩略图是一项常见的任务,特别是在开发图形用户界面、网站或移动应用时。PNG格式因其支持透明度而受到欢迎,但缩略图的生成需要考虑保持图像质量和透明效果。以下是一些关于如何在...

    java上传文件(图片)工具类,可直接使用

    java上传文件util包,可直接使用,需将地址改为自己的存储地址,

    java开发常用工具类大全,程序员必备工具

    Java开发是软件工程中的核心部分,对于程序员来说,掌握一套高效、全面的工具类库能够极大地提高工作效率。本文将详细解析“java开发常用工具类大全”中涉及的关键知识点,包括但不限于输入字符校验、数据转换、网络...

    java图片处理工具类JAR包 java-image-scalingjar

    java图片处理工具类JAR包 java-image-scalingjar

    DDS图片缩略图显示工具DDS_viewer

    这款工具的特色在于其缩略图功能,使得用户在不打开每个文件的情况下,也能对文件夹中的多个DDS图片有一个直观的了解。 DDS文件通常包含颜色数据、压缩格式以及MIP映射级别等信息,其中MIP映射是提高图形性能的一种...

    WPF利用缩略图实现图片放大缩小

    在本文中,我们将深入探讨如何在Windows Presentation Foundation (WPF) 中利用缩略图实现图片的放大缩小功能。WPF是微软.NET Framework的一部分,提供了一种强大的方式来创建丰富的、交互式的桌面应用程序。 首先...

    图片等比例缩放问题

    ### 图片等比例缩放问题解析 在处理图像时,经常需要对图片进行等比例缩放,以适应不同的显示需求或优化存储空间。本篇文章将详细介绍如何实现图片的等比例缩放,包括缩放的基本原理、实现方法以及注意事项。 ####...

    JAVA生成WORD工具类

    这个“JAVA生成WORD工具类”很可能是提供了一种便捷的方式,帮助开发者通过Java代码来创建和操作Microsoft Word文档。下面我们将深入探讨如何在Java中实现Word文档的生成,并结合提供的标签“源码”和“工具”,分享...

    java图片浏览管理系统

    7. **图片预览技术**:系统可能会利用thumbnailator或其他类似的库来生成图片缩略图,提供快速预览的功能。 8. **文件遍历与目录树结构**:系统可能需要展示图片所在的文件夹结构,这就需要用到递归遍历文件夹的...

    【ASP.NET编程知识】ASP.NET简单好用功能齐全图片上传工具类(水印、缩略图、裁剪等).docx

    本文将详细介绍一个 ASP.NET 图片上传工具类,该工具类支持水印、缩略图、裁剪等功能。该工具类的使用方法非常简单,只需要实例化 UploadImage 对象,并设置相关参数,即可实现图片上传、水印添加、缩略图生成和裁剪...

    java对图片进行操作.rar_java 图片剪裁_java图片_图片

    本资源“java对图片进行操作.rar”提供了一种用Java进行图像操作的工具类,特别关注于图片的剪裁、重置大小以及按比例缩小等功能。以下是关于这些功能的详细解释和实现方法。 首先,图片剪裁是调整图像大小并提取其...

    JPG图片缩略图与原图不一致(VC6源码)

    网上流传的‘一张令所有人吃惊的图片’,是一张椅子的图片,但是,如果你的系统是XP,把它下载后保存到任意一个文件夹中,打开文件夹,用缩略图的方式查看,会看到图片的缩略图是一个机器女人坐在地上。 经过一番研究...

    JspSmart_img.rar_JAVA 缩略图_JSP上传_img缩略图_jspsmar_jspsmart

    "JAVA 缩略图" 指的是通过编程手段将原始图片按比例缩小,创建一个尺寸较小但保持原图比例的版本,这样可以节省服务器存储空间,加快网页加载速度,并且便于用户在页面上预览大图。在Java中,这一过程通常涉及到对...

    php 自动缩略图,php智能生成缩略图

    在网页设计和开发中,图片是重要的组成部分,但大尺寸的图片可能会导致页面加载速度变慢,影响用户体验。为了优化这一问题,PHP 提供了一种...通过深入学习和实践,我们可以创建出更加高效、功能丰富的图片处理工具。

    tga格式缩略图查看插件

    总的来说,TGA格式缩略图查看插件是提升Windows系统中处理TGA图像体验的重要工具。通过这样的插件,用户可以更方便地管理和预览TGA图像,尤其对于经常处理这类格式的专业人士而言,它的价值不言而喻。

    java反射工具类 ReflectionUtils

    该工具类下载后拷贝到你要用的包,只需该包名即可

Global site tag (gtag.js) - Google Analytics