制作缩略图

package com.huawei.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
* @author Administrator
*
*/
public class ImageUtil {

//“相框”的宽高
private static final int WIDTH=300;
private static final int HEIGHT=200;

public static void preview(File src,File out,String format) throws Exception{
//将文件 映射到内存中
BufferedImage image = ImageIO.read(src);
//得到原始图片的宽高
int height = image.getHeight();
int width = image.getWidth();

//计算目标图片的宽高

int x = WIDTH;
int y = HEIGHT;

if(width*y>height*x){
y = height*x/width;
}
if(width*y<height*x){
x = width*y/height;
}

System.out.println(width);
System.out.println(height);
System.out.println(width*1.0/height);
System.out.println(x);
System.out.println(y);
System.out.println(x*1.0/y);
//是相框
BufferedImage new_Image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.SCALE_SMOOTH);
//创建画笔
Graphics2D graphics2d = new_Image.createGraphics();
//设置白色
graphics2d.setColor(new Color(255, 255, 255));
//填充颜色
graphics2d.fillRect(0, 0, WIDTH, HEIGHT);
//得到缩放以后的图片
Image target = image.getScaledInstance(x, y, BufferedImage.SCALE_SMOOTH);

graphics2d.drawImage(target, (WIDTH-x)/2, (HEIGHT-y)/2, x, y, null);
ImageIO.write(new_Image, format, out);

}

public static void main(String[] args) throws Exception{
preview(new File("D:/bg.jpg"),new File("D:/bg1.jpg"),"jpg");
}

}

转载于:https://www.cnblogs.com/hwgok/p/5874442.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值