java基础---->Java中图片的缩放

  缩略图代表网页上或计算机中图片经压缩方式处理后的小图 ,其中通常会包含指向完整大小的图片的超链接。缩略图用于在 Web 浏览器中更加迅速地装入图形或图片较多的网页。今天,我们就开始java中图像的缩略图的学习。thumbnailator框架的使用:  Java三方---->Thumbnailator框架的使用

使用jdk自带bufferedImage

项目结构如下:

一、 JDKZoomImage.java

package com.huhx.jdk;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
 * writer: huhx
 */
public class JDKZoomImage {
    public void zoomImage() {
        BufferedImage bufferedImage = null;
        File file = new File("image/huhx.jpg");
        if (file.canRead()) {
            try {
                bufferedImage = ImageIO.read(file);
                bufferedImage = zoomInImage(bufferedImage, 5);
                ImageIO.write(bufferedImage, "JPG", new File("image/zoomHuhx.jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private BufferedImage zoomInImage(BufferedImage bufferedImage, int times) {
        int width = bufferedImage.getWidth() / times;
        int height = bufferedImage.getHeight() / times;

        BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());
        Graphics graphics = newImage.getGraphics();
        graphics.drawImage(bufferedImage, 0, 0, width, height, null);
        graphics.dispose();
        return newImage;
    }

    public static void main(String[] args) {
        new JDKZoomImage().zoomImage();
    }
}

二、 结果如下,生成图片zoomHuhx.jpg

huhx.jpg       1366 * 768      398KB

zoomHuhx.jpg   273*153          18.4KB

使用thumbnailator框架

thumbnailator包的地址: http://pan.baidu.com/s/1jI8jjfg。humbnailator框架的具体使用,请参见我的另外博客:Java三方---->Thumbnailator框架的使用

ThumbnailatorImage.java的内容如下:

package com.huhx.jdk;

import java.io.File;
import java.io.IOException;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;

/**
 * @author huhx
 */
public class ThumbnailatorImage {
    // 根据缩放比缩放图片
    public void zoomImageWithScale() {
        try {
            Thumbnails.of(new File("image/huhx.jpg").listFiles()).scale(0.2).outputFormat("jpg").toFiles(Rename.PREFIX_DOT_THUMBNAIL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 根据固定大小缩放图片
    public void zoomImageWithSize() {
        try {
            Thumbnails.of(new File("image/huhx.jpg").listFiles()).size(640, 480).outputFormat("jpg").toFiles(Rename.PREFIX_DOT_THUMBNAIL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ThumbnailatorImage image = new ThumbnailatorImage();
        image.zoomImageWithScale();
        image.zoomImageWithSize();
    }
}
原文地址:https://www.cnblogs.com/huhx/p/javaThumbnailator.html