private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename) throws InterruptedException, FileNotFoundException, IOException { // load p_w_picpath from filename Image p_w_picpath = Toolkit.getDefaultToolkit().getImage(filename); MediaTracker mediaTracker = new MediaTracker(new Container()); mediaTracker.addImage(p_w_picpath, 0); mediaTracker.waitForID(0); // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny()); // determine thumbnail size from WIDTH and HEIGHT double thumbRatio = (double)thumbWidth / (double)thumbHeight; int p_w_picpathWidth = p_w_picpath.getWidth(null); int p_w_picpathHeight = p_w_picpath.getHeight(null); double p_w_picpathRatio = (double)p_w_picpathWidth / (double)p_w_picpathHeight; if (thumbRatio < p_w_picpathRatio) { thumbHeight = (int)(thumbWidth / p_w_picpathRatio); } else { thumbWidth = (int)(thumbHeight * p_w_picpathRatio); } // draw original p_w_picpath to thumbnail p_w_picpath object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(p_w_picpath, 0, 0, thumbWidth, thumbHeight, null); // save thumbnail p_w_picpath to outFilename BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float)quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); }
创建图片的缩略图
精选 转载上一篇:使用NIO进行快速的文件拷贝
下一篇:创建 JSON 格式的数据
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章