图像操作工具类

来源:互联网 发布:小米平板1刷windows 编辑:程序博客网 时间:2024/06/07 22:18
  1. package cn.itcast.bbs.util; 
  2.  
  3. import java.awt.Dimension; 
  4. import java.awt.Image; 
  5. import java.awt.image.BufferedImage; 
  6. import java.awt.image.PixelGrabber; 
  7. import java.io.File; 
  8. import java.io.IOException; 
  9. import java.util.Iterator; 
  10. import java.util.Locale; 
  11.  
  12. import javax.imageio.IIOImage; 
  13. import javax.imageio.ImageIO; 
  14. import javax.imageio.ImageWriteParam;
  15. import javax.imageio.ImageWriter; 
  16. import javax.imageio.plugins.jpeg.JPEGImageWriteParam; 
  17. import javax.imageio.stream.ImageOutputStream; 
  18.  
  19. /**
  20. * Utilities methods for image manipulation. It does not support writting of GIF images, but it can read from. GIF images will be saved as PNG.
  21. *
  22. * @author Rafael Steil
  23. * @version $Id: ImageUtils.java,v 1.23 2007/09/09 01:05:22 rafaelsteil Exp $
  24. */ 
  25. public class ImageUtils { 
  26.     public staticfinal int IMAGE_UNKNOWN = -1
  27.     public staticfinal int IMAGE_JPEG =0
  28.     public staticfinal int IMAGE_PNG =1
  29.     public staticfinal int IMAGE_GIF =2
  30.      
  31.     /**
  32.      * Resizes an image
  33.      *
  34.      * @param imgName
  35.      *            The image name to resize. Must be the complet path to the file
  36.      * @param type
  37.      *            int
  38.      * @param maxWidth
  39.      *            The image's max width
  40.      * @param maxHeight
  41.      *            The image's max height
  42.      * @return A resized <code>BufferedImage</code>
  43.      */ 
  44.     public static BufferedImage resizeImage(String imgName,int type, int maxWidth,int maxHeight) { 
  45.         try
  46.             return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight); 
  47.         } catch (IOException e) { 
  48.             throw new RuntimeException(e); 
  49.         } 
  50.     } 
  51.      
  52.     /**
  53.      * Resizes an image.
  54.      *
  55.      * @param image
  56.      *            The image to resize
  57.      * @param maxWidth
  58.      *            The image's max width
  59.      * @param maxHeight
  60.      *            The image's max height
  61.      * @return A resized <code>BufferedImage</code>
  62.      * @param type
  63.      *            int
  64.      */ 
  65.     public static BufferedImage resizeImage(BufferedImage image,int type, int maxWidth,int maxHeight) { 
  66.         Dimension largestDimension = new Dimension(maxWidth, maxHeight); 
  67.          
  68.         // Original size 
  69.         int imageWidth = image.getWidth(null); 
  70.         int imageHeight = image.getHeight(null); 
  71.          
  72.         float aspectRatio = (float) imageWidth / imageHeight; 
  73.          
  74.         if (imageWidth > maxWidth || imageHeight > maxHeight) { 
  75.             if ((float) largestDimension.width / largestDimension.height > aspectRatio) { 
  76.                 largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio); 
  77.             } else
  78.                 largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio); 
  79.             } 
  80.              
  81.             imageWidth = largestDimension.width; 
  82.             imageHeight = largestDimension.height; 
  83.         } 
  84.          
  85.         return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight); 
  86.     } 
  87.      
  88.     /**
  89.      * Saves an image to the disk.
  90.      *
  91.      * @param image
  92.      *            The image to save
  93.      * @param toFileName
  94.      *            The filename to use
  95.      * @param type
  96.      *            The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
  97.      * @return <code>false</code> if no appropriate writer is found
  98.      */ 
  99.     public staticboolean saveImage(BufferedImage image, String toFileName,int type) { 
  100.         try
  101.             return ImageIO.write(image, type == IMAGE_JPEG ?"jpg" : "png",new File(toFileName)); 
  102.         } catch (IOException e) { 
  103.             throw new RuntimeException(e); 
  104.         } 
  105.     } 
  106.      
  107.     /**
  108.      * Compress and save an image to the disk. Currently this method only supports JPEG images.
  109.      *
  110.      * @param image
  111.      *            The image to save
  112.      * @param toFileName
  113.      *            The filename to use
  114.      * @param type
  115.      *            The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
  116.      */ 
  117.     @SuppressWarnings("unchecked"
  118.     public staticvoid saveCompressedImage(BufferedImage image, String toFileName,int type) { 
  119.         try
  120.             if (type == IMAGE_PNG) { 
  121.                 throw new UnsupportedOperationException("PNG compression not implemented"); 
  122.             } 
  123.              
  124.             Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); 
  125.             ImageWriter writer; 
  126.             writer = (ImageWriter) iter.next(); 
  127.              
  128.             ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName)); 
  129.             writer.setOutput(ios); 
  130.              
  131.             ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault()); 
  132.              
  133.             iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 
  134.             iwparam.setCompressionQuality(0.7F); 
  135.              
  136.             writer.write(null, new IIOImage(image, null,null), iwparam); 
  137.              
  138.             ios.flush(); 
  139.             writer.dispose(); 
  140.             ios.close(); 
  141.         } catch (IOException e) { 
  142.             throw new RuntimeException(e); 
  143.         } 
  144.     } 
  145.      
  146.     /**
  147.      * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can function on a completely headless system. This especially includes Linux and Unix systems that do not have
  148.      * the X11 libraries installed, which are required for the AWT subsystem to operate. This method uses nearest neighbor approximation, so it's quite fast. Unfortunately, the result is nowhere near
  149.      * as nice looking as the createHeadlessSmoothBufferedImage method.
  150.      *
  151.      * @param image
  152.      *            The image to convert
  153.      * @param w
  154.      *            The desired image width
  155.      * @param h
  156.      *            The desired image height
  157.      * @return The converted image
  158.      * @param type
  159.      *            int
  160.      */ 
  161.     public static BufferedImage createHeadlessBufferedImage(BufferedImage image,int type, int width,int height) { 
  162.         if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) { 
  163.             type = BufferedImage.TYPE_INT_ARGB; 
  164.         } else
  165.             type = BufferedImage.TYPE_INT_RGB; 
  166.         } 
  167.          
  168.         BufferedImage bi = new BufferedImage(width, height, type); 
  169.          
  170.         for (int y =0; y < height; y++) { 
  171.             for (int x =0; x < width; x++) { 
  172.                 bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height)); 
  173.             } 
  174.         } 
  175.          
  176.         return bi; 
  177.     } 
  178.      
  179.     /**
  180.      * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can function on a completely headless system. This especially includes Linux and Unix systems that do not have
  181.      * the X11 libraries installed, which are required for the AWT subsystem to operate. The resulting image will be smoothly scaled using bilinear filtering.
  182.      *
  183.      * @param source
  184.      *            The image to convert
  185.      * @param w
  186.      *            The desired image width
  187.      * @param h
  188.      *            The desired image height
  189.      * @return The converted image
  190.      * @param type
  191.      *            int
  192.      */ 
  193.     public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source,int type, int width,int height) { 
  194.         if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) { 
  195.             type = BufferedImage.TYPE_INT_ARGB; 
  196.         } else
  197.             type = BufferedImage.TYPE_INT_RGB; 
  198.         } 
  199.          
  200.         BufferedImage dest = new BufferedImage(width, height, type); 
  201.          
  202.         int sourcex; 
  203.         int sourcey; 
  204.          
  205.         double scalex = (double) width / source.getWidth(); 
  206.         double scaley = (double) height / source.getHeight(); 
  207.          
  208.         int x1; 
  209.         int y1; 
  210.          
  211.         double xdiff; 
  212.         double ydiff; 
  213.          
  214.         int rgb; 
  215.         int rgb1; 
  216.         int rgb2; 
  217.          
  218.         for (int y =0; y < height; y++) { 
  219.             sourcey = y * source.getHeight() / dest.getHeight(); 
  220.             ydiff = scale(y, scaley) - sourcey; 
  221.              
  222.             for (int x =0; x < width; x++) { 
  223.                 sourcex = x * source.getWidth() / dest.getWidth(); 
  224.                 xdiff = scale(x, scalex) - sourcex; 
  225.                  
  226.                 x1 = Math.min(source.getWidth() - 1, sourcex + 1); 
  227.                 y1 = Math.min(source.getHeight() - 1, sourcey + 1); 
  228.                  
  229.                 rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey), xdiff); 
  230.                 rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff); 
  231.                  
  232.                 rgb = getRGBInterpolation(rgb1, rgb2, ydiff); 
  233.                  
  234.                 dest.setRGB(x, y, rgb); 
  235.             } 
  236.         } 
  237.          
  238.         return dest; 
  239.     } 
  240.      
  241.     private staticdouble scale(int point,double scale) { 
  242.         return point / scale; 
  243.     } 
  244.      
  245.     private staticint getRGBInterpolation(int value1,int value2, double distance) { 
  246.         int alpha1 = (value1 & 0xFF000000) >>> 24
  247.         int red1 = (value1 &0x00FF0000) >> 16
  248.         int green1 = (value1 & 0x0000FF00) >> 8
  249.         int blue1 = (value1 &0x000000FF); 
  250.          
  251.         int alpha2 = (value2 &0xFF000000) >>> 24
  252.         int red2 = (value2 & 0x00FF0000) >> 16
  253.         int green2 = (value2 &0x0000FF00) >> 8
  254.         int blue2 = (value2 & 0x000000FF); 
  255.          
  256.         int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) <<24) | ((int) (red1 * (1.0 - distance) + red2 * distance) <<16
  257.                 | ((int) (green1 * (1.0 - distance) + green2 * distance) <<8) | (int) (blue1 * (1.0 - distance) + blue2 * distance); 
  258.          
  259.         return rgb; 
  260.     } 
  261.      
  262.     /**
  263.      * Determines if the image has transparent pixels.
  264.      *
  265.      * @param image
  266.      *            The image to check for transparent pixel.s
  267.      * @return <code>true</code> of <code>false</code>, according to the result
  268.      */ 
  269.     public staticboolean hasAlpha(Image image) { 
  270.         try
  271.             PixelGrabber pg = new PixelGrabber(image,0, 0,1, 1,false); 
  272.             pg.grabPixels(); 
  273.              
  274.             return pg.getColorModel().hasAlpha(); 
  275.         } catch (InterruptedException e) { 
  276.             return false
  277.         } 
  278.     } 
0 0
原创粉丝点击