package com.u.image; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import java.io.File; import javax.imageio.ImageIO; public class Lessen { public Lessen() { } public static BufferedImage resize(BufferedImage source, int targetw, int targeth) { // targetw,targeth分别表示目标长和宽 int type = source.getType(); BufferedImage target = null; double sx = (double) targetw / source.getWidth(); double sy = (double) targeth / source.getHeight(); // 这里想实现在targetw,targeth范围内实现等比缩放。如果不需要等比缩放 // 则将下面的if else语句注释即可 if (sx > sy) { sx = sy; targetw = (int) (sx * source.getWidth()); } else { sy = sx; targeth = (int) (sy * source.getHeight()); } if (type == BufferedImage.TYPE_CUSTOM) { // handmade 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(); // smoother than exlax: 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) throws Exception { BufferedImage srcimage; // string ex = // fromfilestr.substring(fromfilestr.indexof("."),fromfilestr.length()); String imgtype = "jpeg"; if (fromfilestr.toLowerCase().endsWith(".png")) { imgtype = "png"; } // system.out.println(ex); File savefile = new File(savetofilestr); File fromfile = new File(fromfilestr); srcimage = ImageIO.read(fromfile); if (width > 0 || hight > 0) { srcimage = resize(srcimage, width, hight); } ImageIO.write(srcimage, imgtype, savefile); } public static void main(String argv[]) { /* * try { // 参数1(from),参数2(to),参数3(宽),参数4(高) * saveimageasjpg("F:\\DSC_0272.JPG", "F:\\2.jpg", 800, 600); } catch * (Exception e) { e.printStackTrace(); } */ // http://www.111cn.net/jsp/Java/34831.htm System.out.println(800 / 600.0); System.out.println(800 / 1.5); System.out.println(4608 / 3072.0); } }