Home  >  Article  >  Java  >  Detailed explanation of the implementation of image scaling, cutting, type conversion, watermarking and other functions in Java

Detailed explanation of the implementation of image scaling, cutting, type conversion, watermarking and other functions in Java

巴扎黑
巴扎黑Original
2017-08-01 11:36:241619browse

The following common functions can be realized: scaling images, cutting images, image type conversion, color to black and white, text watermark, picture watermark, etc.

The code is as follows Copy the code
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
* Image processing tools:

* Functions: scaling images, cutting images, image type conversion, color to black and white, text watermarks, picture watermarks, etc.
* @author Administrator
*/
public class ImageUtils {

/**
   * Several common image formats
 */
public static String IMAGE_TYPE_GIF = "gif";// Graphics Interchange Format
public static String IMAGE_TYPE_JPG = "jpg";// Joint Photographic Experts Group
Public static String IMAGE_TYPE_JPEG = "jpeg"; // Joint Photo Experts Group
public static String IMAGE_TYPE_BMP = "bmp"; // Abbreviation for English Bitmap, which is the standard image file format in the Windows operating system
public static String IMAGE_TYPE_PNG = "png"; // Portable network graphics
public static String IMAGE_TYPE_PSD = "psd"; // Photoshop's special format Photoshop

/**
     * Program entry: for testing
     * @param args
   */
public static void main(String[] args) {
                                                                                          out out using         using ’’s ’ ’ s using ‐ ‐out‐out‐out‐right args) {
​                                                         using using using using using args. Test OK
                                                                                        using height and width            use using using  ‐                                     through using using using using using using out out out out out out out out out Out out out out out out out out ’s to ’s to            . / 2-Cut image:
                                                                                                                                                                                 through out through pixel              out’’'’’’’’’’’ceoopce’cecerceceps togetherceps togetherceps togethercembcececece rightce rightomp rightce rightomp right right rightomp right right‐‐‐‐‐‐out‐‐outir‐to‐outir‐thir's‐​thirty-thir irst. ); // Test OK
// Method 2: Specify the number of rows and columns of the slice

ImageUtils.cut2("e:/abc.jpg", "e:/", 2, 2 ); // Test OK

// Method 3: Specify the width and height of the slice
          ImageUtils.cut3("e:/abc.jpg", "e:/", 300, 300 ); // Test OK

                                                                     
        ImageUtils.convert("e:/abc.jpg", "GIF", "e:/abc_convert.gif");//Test OK

                                                                                          ImageUtils. /abc.jpg "," e: /abc_gray.jpg "); // Test ok

// 5- Add text watermark to the picture:
// Method 1:

Imageutils.pressterxt (" I am a watermark text ", "e:/abc.jpg","e:/abc_pressText.jpg","宋体",Font.BOLD,Color.white,80, 0, 0, 0.5f);//Test OK

                                                            .
    ImageUtils.pressText2("I am also a watermark text", "e:/abc.jpg", "e:/abc_pressText2.jpg", "Heold", 36, Color.white, 80, 0, 0, 0.5f); //Test OK

                                                                                                                                                          // 6-Add image watermark to the picture:

          ImageUtils.pressImage("e:/abc2.jpg", "e:/abc.jpg", "e:/abc_pressImage.jpg", 0, 0, 0.5f);//Test OK
}

    /**
              * Scale the image (scaling proportionally)
                                                                                                                                                        use using  -                                                                                */
    public final static void scale(String srcImageFile, String result,
            int scale, boolean flag) {
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
            int width = src.getWidth(); // 得到源图宽
            int height = src.getHeight(); // 得到源图长
            if (flag) {// 放大
                width = width * scale;
                height = height * scale;
            } else {// 缩小
                width = width / scale;
                height = height / scale;
            }
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_DEFAULT);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
                                                                                                                                                              use using
      ’ using ’ s srcImageFile ’s-'s srcImageFile
’ to
 @param bb Whether filler is needed when the proportion is wrong: true means filler; false means no filler;
*/
    public final static void scale2(String srcImageFile, String result, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            File f = new File(srcImageFile);
            BufferedImage bi = ImageIO.read(f);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue()
                            / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(AffineTransform
                        .getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {//补白
                BufferedImage image = new BufferedImage(width, height,
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                g.dispose();
                itemp = image;
            }
            ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   
    /**
​​ Coordinate Y
 ​ * @param width Target slice width
 ​ * @param height Target slice height
 ​*/
    public final static void cut(String srcImageFile, String result,
            int x, int y, int width, int height) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "JPEG", new File(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    /**
     * 图像切割(指定切片的行数和列数)
     * @param srcImageFile 源图像地址
     * @param descDir 切片目标文件夹
     * @param rows 目标切片行数。默认2,必须是范围 [1, 20] 之内
* @param cols The number of target slicing columns. Default 2, must be within the range [1, 20]
                                                                                                                                                                                                     ​rows> ;20) rows = 2; // Number of slicing rows
                                                                                        use use using using using using ‐ ‐                     through out using   through   using through using using   through   through through through out through through through through through through through through ’ s ’ through ’ ’ ‐ ‐ ‐ ‐‐ ‐ ‐ ‐ to File(srcImageFile));
int srcWidth = bi.getHeight(); // Source image width
int srcHeight = bi.getWidth(); // Source image height
if (srcWidth > 0 && srcHeight &g t; 0) {
           Image img; int destWidth = srcWidth; //The width of each slice
                                                           int destHeight = srcHeight; // The width of each slice Height
                                                                                                                                                              . } else {
                            destWidth = (int) Math.floor(srcWidth / cols) + 1;
}
                                                                                                               ight = (int) Math.floor(srcWidth / rows) + 1;
                                                                                                                                                                             . /Improvement ideas: Can multi-threading be used to speed up cutting? for (int i = 0; i < rows; i++) {
parameters They are image starting point coordinates and wide heights //: cropImageFilter (int x, int y, int width, int height)
CropFilter = New CropimageFilter (J * Destwidth, I * Destheight,
DestWidth, Destheight);
IMG = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(),                                                                                                                                                                                                                                                                                                                     destHeight,                                 , 0, null); // Draw the reduced image
                                                                                                                                                                 Dir
                                                                                                            " + j + ".jpg");
                                                                                                       

/**
        * Image cutting (specify the width and height of the slice)
                                                                                                                                                       . Default 200
* @param destHeight target slice height. Default 150
*/
public final static void cut3(String srcImageFile, String descDir,
int destWidth, int destHeight) {
try {
if(destWidth<=0) = 200; // slice width
if(destHeight<=0) destHeight = 150; // Slice height
                                                                                                                                                                                                            Read the source image
         BufferedImage bi = ImageIO.read(new File(srcImageFile)); Image width
          int srcHeight = bi.getWidth(); // Source image height
                                                  use using srcHeight ’ s using ImageFilter cropFilter;
           Image image = bi.getScaledInstance(srcWidth, srcHeight , Image. SCALE_DEFAULT); if (srcWidth % destWidth == 0) {
cols = srcWidth / destWidth;
                                                                                                                                If (srcHeight % destHeight == 0) {
                                                                                                                            {
                                                                                                                          Cutting speed
                                                                                                                                                     ; rows; i++) {
  mageFilter(int x,int y,int width, int height)
cropFilter = New CropimageFilter (J * Destwidth, I * Destheight,
destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(),                                                                                                                                                                                                                                                                                                                     destHeight,                                 , 0, null); // Draw the reduced image
                                                                                                                                                                 Dir
                                                                                                            " + j + ".jpg");
                                                                                                       

/**
* 图像类型转换:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG
     * @param srcImageFile 源图像地址
     * @param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等
     * @param destImageFile 目标图像地址
     */
    public final static void convert(String srcImageFile, String formatName, String destImageFile) {
        try {
            File f = new File(srcImageFile);
            f.canRead();
            f.canWrite();
            BufferedImage src = ImageIO.read(f);
            ImageIO.write(src, formatName, new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
      * Convert color to black and white
      * @param srcImageFile Source image address
     * @param destImageFile Destination image address
    */
    public final static void gray(String srcImageFile, String destImageFile) {
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile));
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorConvertOp op = new ColorConvertOp(cs, null);
            src = op.filter(src, null);
            ImageIO.write(src, "JPEG", new File(destImageFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
       * Add text watermark to the picture
     * @param pressText watermark text
    * @param srcImageFile source image address
    * @param destImageFile destination image address
     * @param fontName font name of the watermark
      * @param fontStyle watermark font style
* @param color font color of the watermark
* @param fontSize font size of the watermark
* @param x correction value
* @param y correction value
* @param alpha transparency: alpha must be within the range [0.0, 1.0] (inclusive) boundary value) a floating point number
*/
    public final static void pressText(String pressText,
            String srcImageFile, String destImageFile, String fontName,
            int fontStyle, Color color, int fontSize,int x,
            int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                    / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));// 输出到文件流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
       * Add text watermark to the picture
     * @param pressText watermark text
    * @param srcImageFile source image address
    * @param destImageFile destination image address
     * @param fontName font name
     * @param fontStyle font style
* @param color font Color
      * @param fontSize font size
                                                                                                                                                                                               
 */
    public final static void pressText2(String pressText, String srcImageFile,String destImageFile,
            String fontName, int fontStyle, Color color, int fontSize, int x,
            int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                    / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
       * Add image watermark to the picture
     * @param pressImg watermark image
    * @param srcImageFile source image address
    * @param destImageFile destination image address
     * @param x correction value. Default is in the middle
* @param y correction value. Default is in the middle
  * @param alpha transparency: alpha must be a floating point number within the range [0.0, 1.0] (including boundary values)
 */
    public final static void pressImage(String pressImg, String srcImageFile,String destImageFile,
            int x, int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src_biao, (wideth - wideth_biao) / 2,
                    (height - height_biao) / 2, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image,  "JPEG", new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
       * Calculate the length of text (one Chinese character is counted as two characters)
          * @param text
          * @return
     */
    public final static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }
}

The above is the detailed content of Detailed explanation of the implementation of image scaling, cutting, type conversion, watermarking and other functions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn