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

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 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 if(destHeight                                                                                                                                                                                                            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             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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment