java读取照片生成缩略图

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.geom.AffineTransform;
import java.io.File;

public class Test {
public static BufferedImage resize(BufferedImage source, int targetW,
int targetH, boolean proportion) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
if (proportion) {
if (sx > sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
} else {
sy = sx;
targetH = (int) (sy * source.getHeight());
}
}
if (type == BufferedImage.TYPE_CUSTOM) {
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}

public static void saveImageAsJpg(String fromFileStr, String saveToFileStr,
int width, int hight, boolean proportion){
try {
BufferedImage srcImage;
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}else if(fromFileStr.toLowerCase().endsWith(".bmp")){
imgType = "BMP";
}
File saveFile = new File(saveToFileStr);
File fromFile = new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if (width > 0 || hight > 0) {
srcImage = resize(srcImage, width, hight, proportion);
}
ImageIO.write(srcImage, imgType, saveFile);
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String argv[]) {
long start = System.currentTimeMillis();
String input = "E:/Baicheng03.jpg";
String output = "D:/Baicheng03.jpg";
int X = 360;
int Y = 240;
boolean proportion = true;
Test.saveImageAsJpg(input, output, X, Y, proportion);
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值