一个JAVA图形缩放处理工具类

来源:互联网 发布:web压力测试软件 编辑:程序博客网 时间:2024/05/04 11:05
 调用的例子
  1. import java.io.FileOutputStream;
  2. import java.io.IOException;

  3. import javax.imageio.ImageIO;

  4. public class T {
  5.   public static void main(String[] args) throws Exception, IOException {
  6.     ImageIO.write(ImageUtils.resizeImage("d:/www.java2000.net.gif", ImageUtils.IMAGE_GIF, 3020),
  7.         "JPEG"new FileOutputStream("d:/test.jpg"));
  8.   }
  9. }

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

原创粉丝点击