`

图片工具1

 
阅读更多
ImageUtils
/*
 * Copyright (c) JForum Team
 * All rights reserved.

 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided 
 * that the following conditions are met:

 * 1) Redistributions of source code must retain the above 
 * copyright notice, this list of conditions and the 
 * following  disclaimer.
 * 2)  Redistributions in binary form must reproduce the 
 * above copyright notice, this list of conditions and 
 * the following disclaimer in the documentation and/or 
 * other materials provided with the distribution.
 * 3) Neither the name of "Rafael Steil" nor 
 * the names of its contributors may be used to endorse 
 * or promote products derived from this software without 
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
 * IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
 * 
 * This file creation date: 21/04/2004 - 19:54:16
 * The JForum Project
 * http://www.jforum.net
 */

import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;


/**
 * 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.
 * 
 * @author Rafael Steil
 * @version $Id: ImageUtils.java,v 1.23 2007/09/09 01:05:22 rafaelsteil Exp $
 */
public class ImageUtils
{
  public static final int IMAGE_UNKNOWN = -1;
  public static final int IMAGE_JPEG = 0;
  public static final int IMAGE_PNG = 1;
  public static final int IMAGE_GIF = 2;

  /**
   * Resizes an image
   * 
   * @param imgName The image name to resize. Must be the complet path to the file
   * @param type int
   * @param maxWidth The image's max width
   * @param maxHeight The image's max height
   * @return A resized <code>BufferedImage</code>
   */
  public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight)
  {
    try {
      return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * Resizes an image.
   * 
   * @param image
   *            The image to resize
   * @param maxWidth
   *            The image's max width
   * @param maxHeight
   *            The image's max height
   * @return A resized <code>BufferedImage</code>
   * @param type
   *            int
   */
  public static BufferedImage resizeImage(BufferedImage image, int type, int maxWidth, int maxHeight)
  {
    Dimension largestDimension = new Dimension(maxWidth, maxHeight);

    // Original size
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);

    float aspectRatio = (float) imageWidth / imageHeight;

    if (imageWidth > maxWidth || imageHeight > maxHeight) {
      if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
        largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio);
      }
      else {
        largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio);
      }

      imageWidth = largestDimension.width;
      imageHeight = largestDimension.height;
    }

    return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight);
  }

  /**
   * Saves an image to the disk.
   * 
   * @param image  The image to save
   * @param toFileName The filename to use
   * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
   *  or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
   * @return <code>false</code> if no appropriate writer is found
   */
  public static boolean saveImage(BufferedImage image, String toFileName, int type)
  {
    try {
      return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * Compress and save an image to the disk. Currently this method only supports JPEG images.
   * 
   * @param image The image to save
   * @param toFileName The filename to use
   * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
   * or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
   */
  public static void saveCompressedImage(BufferedImage image, String toFileName, int type)
  {
    try {
      if (type == IMAGE_PNG) {
        throw new UnsupportedOperationException("PNG compression not implemented");
      }

      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer;
      writer = (ImageWriter) iter.next();

      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
      writer.setOutput(ios);

      ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

      iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwparam.setCompressionQuality(0.7F);

      writer.write(null, new IIOImage(image, null, null), iwparam);

      ios.flush();
      writer.dispose();
      ios.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 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 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 as nice looking as the createHeadlessSmoothBufferedImage method.
   * 
   * @param image  The image to convert
   * @param w The desired image width
   * @param h The desired image height
   * @return The converted image
   * @param type int
   */
  public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width, int height)
  {
    if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
      type = BufferedImage.TYPE_INT_ARGB;
    }
    else {
      type = BufferedImage.TYPE_INT_RGB;
    }

    BufferedImage bi = new BufferedImage(width, height, type);

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
      }
    }

    return bi;
  }

  /**
   * 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 the X11 libraries installed, which are required for the AWT subsystem to
   * operate. The resulting image will be smoothly scaled using bilinear filtering.
   * 
   * @param source The image to convert
   * @param w The desired image width
   * @param h The desired image height
   * @return The converted image
   * @param type  int
   */
  public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type, int width, int height)
  {
    if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
      type = BufferedImage.TYPE_INT_ARGB;
    }
    else {
      type = BufferedImage.TYPE_INT_RGB;
    }

    BufferedImage dest = new BufferedImage(width, height, type);

    int sourcex;
    int sourcey;

    double scalex = (double) width / source.getWidth();
    double scaley = (double) height / source.getHeight();

    int x1;
    int y1;

    double xdiff;
    double ydiff;

    int rgb;
    int rgb1;
    int rgb2;

    for (int y = 0; y < height; y++) {
      sourcey = y * source.getHeight() / dest.getHeight();
      ydiff = scale(y, scaley) - sourcey;

      for (int x = 0; x < width; x++) {
        sourcex = x * source.getWidth() / dest.getWidth();
        xdiff = scale(x, scalex) - sourcex;

        x1 = Math.min(source.getWidth() - 1, sourcex + 1);
        y1 = Math.min(source.getHeight() - 1, sourcey + 1);

        rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey), xdiff);
        rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);

        rgb = getRGBInterpolation(rgb1, rgb2, ydiff);

        dest.setRGB(x, y, rgb);
      }
    }

    return dest;
  }

  private static double scale(int point, double scale)
  {
    return point / scale;
  }

  private static int getRGBInterpolation(int value1, int value2, double distance)
  {
    int alpha1 = (value1 & 0xFF000000) >>> 24;
    int red1 = (value1 & 0x00FF0000) >> 16;
    int green1 = (value1 & 0x0000FF00) >> 8;
    int blue1 = (value1 & 0x000000FF);

    int alpha2 = (value2 & 0xFF000000) >>> 24;
    int red2 = (value2 & 0x00FF0000) >> 16;
    int green2 = (value2 & 0x0000FF00) >> 8;
    int blue2 = (value2 & 0x000000FF);

    int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) << 24)
      | ((int) (red1 * (1.0 - distance) + red2 * distance) << 16)
      | ((int) (green1 * (1.0 - distance) + green2 * distance) << 8)
      | (int) (blue1 * (1.0 - distance) + blue2 * distance);

    return rgb;
  }

  /**
   * Determines if the image has transparent pixels.
   * 
   * @param image The image to check for transparent pixel.s
   * @return <code>true</code> of <code>false</code>, according to the result
   */
  public static boolean hasAlpha(Image image)
  {
    try {
      PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
      pg.grabPixels();

      return pg.getColorModel().hasAlpha();
    }
    catch (InterruptedException e) {
      return false;
    }
  }
}

 

分享到:
评论

相关推荐

    网站图片爬虫小工具 网站图片爬虫小工具

    网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具网站图片爬虫小工具...

    LVGL图片转换工具图片转换工具

    LVGL图片转换工具是一款专为LVGL框架设计的实用软件,它使得开发者能够方便地将普通图像文件转换成LVGL可以识别的C语言源代码文件。这个工具采用图形化用户界面,提供直观的操作流程,无论是单个图片还是整个文件夹...

    各种图片合并工具处理小工具

    图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并工具图片合并...

    八爪鱼图片下载工具,可用于下载通过八爪鱼爬取的图片信息

    标题中的“八爪鱼图片下载工具”是一款专为八爪鱼(Octopus)爬虫设计的辅助工具,用于批量下载通过八爪鱼爬取到的图片资源。八爪鱼是一款强大的网页数据采集软件,能够自动化地抓取互联网上的各种信息,包括文字、...

    【精品小工具】Ali智能图片翻译工具,免费版 这是个图片-图片的翻译工具,可以翻译本地和在线图片 可以批量

    Ali智能图片翻译工具,免费版。这是个图片--图片的翻译工具,可以翻译本地和在线图片。可以批量。 本软件使用阿里云的图片翻译接口。 阿里云提供了图片翻译功能,也就是输入中文/英文图片,返回英文或者其它语言的...

    图片压缩小工具

    今天,我们要介绍的是一款名为"ImageResizer.exe"的工具,它以其免安装、低内存占用和强大的实用性,成为了图片压缩领域的优秀选择。 首先,让我们来了解一下ImageResizer.exe的基本操作。这款工具的最大亮点在于其...

    MTK图片转工具Setup1.3.rar

    1. **文件格式转换**:MTK图片转工具可能支持将特定的MTK设备图像格式转换为常见的图片格式(如JPEG、PNG等),以便在其他设备上查看或编辑。 2. **批量处理**:考虑到设备制造商和开发者可能需要处理大量图像,此...

    微信DAT文件转图片工具

    然而,通过特定的工具,如描述中提到的“微信DAT文件转图片工具”,我们可以将这些DAT文件转换成可查看的图像文件。 这个工具是由JAVA编程语言开发的,JAVA是一种广泛使用的跨平台编程语言,具有丰富的库和强大的...

    blob类型图片批量导出工具

    Blob类型图片批量导出工具是一款专门针对存储在数据库中的Blob类型图像数据进行处理的应用程序。Blob,全称为Binary Large Object,是数据库系统中用于存储大量二进制数据的对象类型,通常包括图片、音频、视频等...

    16进制转JPG图片工具

    16进制转JPG图片工具是专为处理这种特定需求而设计的软件,它允许用户将从单片机或其他数据采集设备获取的16进制代码转换成我们常见的JPEG(JPG)图片格式。这种转换过程涉及到数字图像处理、二进制数据解析以及图像...

    Plist图片分解工具

    《Plist图片分解工具:深入理解与应用》 在iOS和macOS开发中,Plist(Property List)文件是一种常见的数据存储格式,用于保存应用程序的配置、设置等数据。然而,Plist文件并非只用于存储文本信息,它也可以包含二...

    php图片裁切工具

    1. **上传图片**:用户上传需要裁剪的图片到服务器,PHP通过$_FILES全局变量接收上传的数据。 2. **读取图片**:使用GD库或Imagick的函数读取上传的图片,如imagecreatefromjpeg()、imagecreatefrompng()等。 3. **...

    JPG图片批量加密解密工具

    "JPG图片批量加密解密工具"就是针对这一需求而设计的专业软件。它能够帮助用户快速、方便地对大量的JPG格式图片进行加密和解密操作,确保隐私和敏感信息的安全。 JPG,全称Joint Photographic Experts Group,是一...

    图片取点工具 取得图片中某点的坐标

    1. **图像加载**:使用图像处理库,如OpenCV或PIL,读取图片文件,将其转化为可操作的数据结构。 2. **交互界面**:设计用户友好的图形用户界面(GUI),让用户能够方便地查看图像,并能选择感兴趣的点。这可以通过...

    VC工具栏图片制作工具

    1. 图标编辑:内置简单的图形编辑功能,允许用户绘制或修改工具栏所需的图标。 2. 多格式支持:支持多种图标格式,如ICO、PNG等,适应不同操作系统和视觉风格的需求。 3. 导入/导出:可以导入现有的图标库,也可以...

    图片批量旋转工具

    1. **安装与启动**:下载并运行“图片批量旋转工具 V2.0.exe”,按照安装向导的指示完成安装。安装完成后,从开始菜单或桌面快捷方式启动软件。 2. **导入图片**:在软件界面上,选择“添加文件”或“添加目录”...

    图片查找工具.v2010.xla

    图片查找工具.v2010加载宏

    电脑图片工具 图片浏览器

    电脑图片工具 图片浏览器 ,图片编辑 切割 去水印等

    Protel99se添加图片工具

    1. 下载并安装“Protel99se添加图片工具”(btp.exe)。 2. 准备需要添加到Protel99se中的BMP图像文件。 3. 运行工具,选择要转换的BMP文件,设置转换参数(如尺寸、分辨率等)。 4. 点击转换按钮,生成适应Protel99...

    java 图片处理工具类 java 图片处理工具类

    java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 java 图片处理工具类 ...

Global site tag (gtag.js) - Google Analytics