public class Thumbnail { private int width; // private int height; private Image img; private int w = 250; private int h = 150; /** * 构造函数 * * @param fileName * String * @throws IOException */ public Thumbnail(String urlName) throws IOException { // 创建URL URL url = new URL(urlName); // 载入图片到输入流 InputStream inputStream = new BufferedInputStream(url.openStream()); img = javax.imageio.ImageIO.read(inputStream); // 构造Image对象 width = img.getWidth(null); // 得到源图宽 height = img.getHeight(null); // 得到源图长 if (inputStream!=null) { inputStream.close(); } } /** * 形成图片二进制数组 * * @param w int 新宽度 * @param h int 新高度 * @throws IOException */ private byte[] resize(){ byte[] m = null; ImageOutputStream imOut =null; InputStream is=null; try{ BufferedImage _image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); _image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图 _image.getGraphics().dispose(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(_image, "JPEG", imOut); is = new ByteArrayInputStream(bs.toByteArray()); m = new byte[is.available()]; is.read(m); }catch(IOException e) { e.printStackTrace(); }finally{ try { if (is!=null) { is.close(); } if (imOut!=null) { imOut.close(); } } catch (IOException e) { // TODO Auto-generated catch block LogUtil.getLogger().warn(e); } } return m; } /** * 按照固定的比例缩放图片 * * @param t double 比例 * @throws IOException */ private byte[] resize(double t) throws IOException { w = (int) (width * t); h = (int) (height * t); return resize(); } /** * 以宽度为基准,等比例放缩图片 * * @param w int 新宽度 * @throws IOException */ private byte[] resizeByWidth(int w) throws IOException { h = (int) (height * w / width); return resize(); } /** * 以高度为基准,等比例缩放图片 * @param h int 新高度 * @throws IOException */ private byte[] resizeByHeight(int h) throws IOException { w = (int) (width * h / height); return resize(); } /** * 高度大于宽度,按照最大高度限制;宽度大于高度,按照醉倒宽度限制。 * 生成最大的等比例缩略图 当图片高度宽度都没有缩略图要求的高度宽度大的时候 就直接按照原始尺寸来保存 * @param w int 最大宽度 * @param h int 最大高度 * @throws IOException */ public byte[] resizeFixLimitHeight(int tThumbWight, int tThumbHeight) throws IOException { w = tThumbWight; // 缩略图的宽度 h = tThumbHeight; // 缩略图高度 if (width >= w && height >= h) { if (width / height > w / h) { return resizeByWidth(w); } else { return resizeByHeight(h); } } else { if (width >= w && height <= h) { return resizeByWidth(w); } else if (width <= w && height >= h) { return resizeByHeight(h); } else if (w >= this.width && h >= this.height) { w = this.width; h = this.height; return resize(); } } return null; } /** * 获取图片原始宽度 getSrcWidth */ public int getSrcWidth() { return width; } /** * 获取图片原始高度 getSrcHeight */ public int getSrcHeight() { return height; } } 我是直接将网站上的图片以图片流的形式保存到mongodb数据库中去的,所以没有生成本地图片,直接将流缩略后保存到数据库中。