在一个3D Web项目使用了图片格式转换,缩放等。
1 //defaultSuffix为jpg,不支持bmp
2 public static final boolean resizeImage(String fileName, String suffix) throws Exception ...{
3 boolean resized= false;
4 BufferedImage input;
5 if(suffix.equalsIgnoreCase("tif")||suffix.equalsIgnoreCase("tiff")||suffix.equalsIgnoreCase("png")) ...{//如果是tiff或者png
6 RenderedImage image = JAI.create("fileload", TurbineServlet.getRealPath(imageRoot + fileName+"."+suffix));
7 WritableRaster raster = image.copyData(null);
8 BufferedImage bi = new BufferedImage( image.getColorModel(), raster, true, null);
9 BufferedImage bi2 = new BufferedImage( maxResizeDimension, bi.getHeight()*maxResizeDimension/bi.getWidth(), BufferedImage.TYPE_INT_RGB);
10 Graphics2D g2 = bi2.createGraphics();
11 g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
12 g2.setBackground(java.awt.Color.WHITE);//把tiff和png转换后的背景设置为白色
13 g2.fillRect(0, 0, maxResizeDimension, bi.getHeight()*maxResizeDimension/bi.getWidth());
14 g2.drawImage(bi, 0, 0, maxResizeDimension, bi.getHeight()*maxResizeDimension/bi.getWidth(), null);
15 PlanarImage pi = PlanarImage.wrapRenderedImage(bi2);
16 JAI.create("FileStore", pi, TurbineServlet.getRealPath(resizeRoot + fileName+"."+defaultSuffix).replaceAll("",""), "JPEG", new JPEGEncodeParam());
17 input = pi.getAsBufferedImage();
18 int w = maxThumbDimension, h = maxThumbDimension;
19
20 BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
21 Graphics2D g = output.createGraphics();
22 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
23 g.drawImage(input,0,0,w,h, null);
24 ImageIO.write(output, defaultSuffix, new File(TurbineServlet.getRealPath(thumbRoot + fileName+"."+defaultSuffix)));
25 }
26 else ...{//如果是gif或者jpg
27 input = ImageIO.read(new File(TurbineServlet.getRealPath(imageRoot + fileName+"."+suffix)));
28 int w = maxThumbDimension, h = maxThumbDimension;
29
30 BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
31 Graphics2D g = output.createGraphics();
32 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
33 g.drawImage(input,0,0,w,h, null);
34 ImageIO.write(output, defaultSuffix, new File(TurbineServlet.getRealPath(thumbRoot + fileName+"."+defaultSuffix)));
35
36 BufferedImage output2 = new BufferedImage(maxResizeDimension, input.getHeight()*maxResizeDimension/input.getWidth(), BufferedImage.TYPE_3BYTE_BGR);
37 Graphics2D g2 = output2.createGraphics();
38 g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
39 g2.drawImage(input,0,0,maxResizeDimension, input.getHeight()*maxResizeDimension/input.getWidth(), null);
40 ImageIO.write(output2, defaultSuffix, new File(TurbineServlet.getRealPath(resizeRoot + fileName+"."+defaultSuffix)));
41 }
42 resized = true;
43 return resized;
44 }
45