-
2004-11-11 @ Tag 应用技巧 人气:8428基本原理是:把原图片读入到缓存中然后获得目标图片一些信息,然后按照放缩比例重新建立一个缓存图片,在新建立得缓存图片上把原图片画上去.
核心代码:
JavaCodepublicstaticvoid zoom() {//目标图片 File input = new File("D:/cnjbb_banner.jpg"); //输出的位置 String output = "D:/work_test/photo/jpeg/"; try{ InputStream imageStream = new FileInputStream(input); //根据目标图片建立一个缓存图片 JPEGImageDecoder decoderFile = JPEGCodec.createJPEGDecoder(imageStream); BufferedImage imageFile = decoderFile.decodeAsBufferedImage(); float zoom = 0.5F;//你要方缩的比例 //获得目标图片的宽高,同时乘以放缩比例得到新图片大小 int w = (int) (imageFile.getWidth() * zoom); int h = (int) (imageFile.getHeight() * zoom); //建立一个新图片的缓存图片 BufferedImage bufImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); FileOutputStream out = new FileOutputStream(output + input.getName()); //从目标图片上获得Graphics以便画在新图片上,最后一个参数是内部无名类,可以用null代替 Graphics g = bufImage.getGraphics(); g.drawImage(imageFile, 0, 0, w, h, new ImageObserver() { public boolean imageUpdate( Image img, int infoflags, int x, int y, int width, int height) { return true; } }); //编码输出 JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(out); jpeg.encode(bufImage); out.flush(); out.close(); imageStream.close(); } catch (Exception e) { e.printStackTrace(); } }根据实际的需求来修改,或者做成servlet,等等 ...
其他格式的图片只要有相应的解码/编码 就可以.
