自定义高度宽度缩小图片

直接上代码:

package com.henu.test;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImgTest {

    public static void createImgThumbnail(String imgSrc, int thumbWidth,
            int thumbHeight, String outFilePath) throws InterruptedException,
            IOException {
        File imageFile = new File(imgSrc);
        BufferedImage image = ImageIO.read(imageFile);
        Integer width = image.getWidth();
        Integer height = image.getHeight();
        double i = (double) width / (double) height;
        double j = (double) thumbWidth / (double) thumbHeight;
        int[] d = new int[2];
        int x = 0;
        int y = 0;
        if (i > j) {
            d[1] = thumbHeight;
            d[0] = (int) (thumbHeight * i);
            y = 0;
            x = (d[0] - thumbWidth) / 2;
        } else {
            d[0] = thumbWidth;
            d[1] = (int) (thumbWidth / i);
            x = 0;
            y = (d[1] - thumbHeight) / 2;
        }
        File outFile = new File(outFilePath);
        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        /* 等比例缩放 */
        BufferedImage newImage = new BufferedImage(d[0], d[1], image.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(image, 0, 0, d[0], d[1], null);
        g.dispose();
        /* 居中剪裁 */
        newImage = newImage.getSubimage(x, y, thumbWidth, thumbHeight);
        ImageIO.write(
                newImage,
                imageFile.getName().substring(
                        imageFile.getName().lastIndexOf(".") + 1), outFile);
    }

    public static void main(String[] args) throws Exception {
        ImgTest.createImgThumbnail("D:/test/2.jpg", 510, 288, 
                "D:/test/test_2.jpg");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值