Thumbnailator is a Java library for creating and manipulating image thumbnails. It provides a simple and easy-to-use API that can easily generate thumbnails and perform various operations such as resizing, rotating, cropping, etc. It supports multiple image formats, including JPEG, PNG, GIF, etc., and can combine multiple operations through chain calls. Thumbnailator also provides rich documentation and examples to help developers get started and use the library quickly. Whether in web applications or desktop applications, Thumbnailator can help developers easily generate and process image thumbnails.
Official website:/p/thumbnailator/
Here are some thumbnailator use cases:
<dependency> <groupId></groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
1. Create thumbnails
import ; import ; import ; public class ThumbnailCreator { public static void main(String[] args) { try { ("") .size(200, 200) .toFile(""); } catch (IOException e) { (); } } }
The above code will create a 200x200 pixel thumbnail from an image file named "" and save it as "".
2. Resize the image
import ; import ; import ; public class ImageResizer { public static void main(String[] args) { try { ("") .scale(0.5) .outputFormat("png") .toFile(""); } catch (IOException e) { (); } } }
The above code will create a 50% size image from an image file named "" and save it as "".
3. Add watermark
import ; import ; import ; import ; public class WatermarkAdder { public static void main(String[] args) { try { ("") .scale(0.8) .watermark(Positions.BOTTOM_RIGHT, (new File("")), 0.5f) .toFile(""); } catch (IOException e) { (); } } }
The above code will create an 80% size image from an image file named "" and add a watermark image with transparency of 0.5 in the lower right corner and save the result as "".
4. Add watermark
It is also very convenient to add a watermark. Our example places the watermark in the upper right corner, and the code is as follows:
(originalPic) .size(2000,1500) .watermark(Positions.TOP_RIGHT, ( new File(picturePath + ".")), 0.5f) .toFile(picturePath + "");
5. Cut
The implementation of the cutting code is as follows:
(originalPic) .sourceRegion(Positions.TOP_RIGHT, 1800, 1800) .size(400, 400) .toFile(picturePath + "");
6. File batch operations in the directory
This function is still very useful. You can operate all pictures in the directory and specify the file name output. For example, specify the prefix, the code is as follows:
(new File("/images/202401/").listFiles()) .size(400, 400) .toFiles(Rename.PREFIX_DOT_THUMBNAIL);
These examples show only a part of the features of thumbnailator, and the library also provides many other features such as rotation, cropping, converting formats, and more. Detailed documentation can be found on the official website of thumbnailator.
7. Batch processing of pictures
/** * Batch processing of pictures * @param srcDirPath Source Directory * @param distDirPath Save the target directory */ @SneakyThrows public static void createImages(String srcDirPath, String distDirPath) { // Check whether the target folder exists File distDir = new File(distDirPath); if (!()) { (); } // Bulk generation File srcDir = new File(srcDirPath); if (()) { // Get the pictures in the source directory: jpg, jpeg, gif, png File[] files = (new FileFilter() { @Override public boolean accept(File pathname) { return isSupportImageType(()); } }); // File name, file type, target picture String fileName, fileType; BufferedImage newImage; for (File file : files) { // File name fileName = (); // File Type fileType = ((".") + 1); // Generate pictures newImage = (file); // Save the picture (newImage, fileType, new File(distDirPath, fileName)); } } }
8. Write image tools
package ; import ; import ; import ; import ; import .*; import ; import ; import ; import ; import ; /** * <p>Image Processing Tools</p> * * @author Earthy * Date 2022/6/13 * @version 1.0 */ public class ImageUtil { /** * Batch processing of pictures * @param srcDirPath Source Directory * @param distDirPath Save the target directory */ @SneakyThrows public static void createImages(String srcDirPath, String distDirPath) { // Check whether the target folder exists File distDir = new File(distDirPath); if (!()) { (); } // Bulk generation File srcDir = new File(srcDirPath); if (()) { // Get the pictures in the source directory: jpg, jpeg, gif, png File[] files = (new FileFilter() { @Override public boolean accept(File pathname) { return isSupportImageType(()); } }); // File name, file type, target picture String fileName, fileType; BufferedImage newImage; for (File file : files) { // File name fileName = (); // File Type fileType = ((".") + 1); // Generate pictures newImage = (file); // Save the picture (newImage, fileType, new File(distDirPath, fileName)); } } } /** * Multiple processing: * 1. Random rotation * 2. Random zoom * 3. Cut to original size * 4. Add random line watermark * 5. Random compression */ @SneakyThrows public static BufferedImage getNewImage(String srcImage) { return getNewImage(new File(srcImage)); } /** * Multiple processing: * 1. Random rotation * 2. Random zoom * 3. Cut to original size * 4. Add random line watermark * 5. Random compression */ @SneakyThrows public static BufferedImage getNewImage(File srcFile) { // Before processing BufferedImage img1 = (srcFile); int w1 = (); int h1 = (); // Picture operation // --- 1. Rotate and enlarge BufferedImage img2 = (img1) // Rotate; // Angle: Positive number: Clockwise Negative number: Clockwise .rotate((-0.5, 0.5)) // Scaling .scale((1.0, 1.05)) // Use the original format .useOriginalFormat() // Save as a BufferedImage object after processing .asBufferedImage(); // The image size after rotation and enlargement int w2 = (); int h2 = (); // --- 2. Cropping, watermarking, compression // Starting point int i = (w2 - w1) / 2; int j = (h2 - h1) / 2; BufferedImage resImage = (img2) /** * Image cropping * ---------------- * The upper left corner of the picture is (0,0) * ---------------- * The first two parameters locate the starting point of the crop; * Parameter 1: The horizontal axis of the starting point * Parameter 2: The vertical coordinate of the point * ---------------- * The last two parameters specify the crop size * Parameter 3: Width * Parameter 4: Height */ .sourceRegion(i, j, w1, h1) // No scaling after cropping .scale(1.0f) // Add line watermark .watermark(Positions.TOP_LEFT, getLineBufferedImage(w1, h1), 0.5f, 0) // Random compression (output quality) .outputQuality((0.85f, 1.0f)) // Output format .useOriginalFormat() //.outputFormat("jpg") .asBufferedImage(); return resImage; } /** * Add text watermark (default upper right corner) * * @param srcImage Original image * @param text Watermark content * @param fontSize Watermark text size * @return */ @SneakyThrows public static BufferedImage addStrWater(String srcImage, String text, int fontSize) { BufferedImage resImage = (srcImage) // No zoom .scale(1.0f) // Add text watermark .watermark(Positions.TOP_RIGHT, getStringBufferedImage(text, fontSize), 0.5f, 10) // The output quality remains unchanged .outputQuality(1.0f) // Output format .useOriginalFormat() .asBufferedImage(); return resImage; } /** * Generate line pictures * ---------------------------- * Transparent background * Specify width and height * Random number of lines, color of lines, and position of lines * ---------------------------- * * @param width width * @param height * @return */ public static BufferedImage getLineBufferedImage(int width, int height) { // Set width and height, picture type BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); // Get Graphics2D Graphics2D g2d = (); // Create compatible images; Transparency TRANSLUCENT represents image data that contains or may contain any alpha values between 0.0 and 1.0. image = ().createCompatibleImage(width, height, ); // implement (); // Create drawing graphics g2d = (); // Set the drawing area (0, 0, width, height); // Draw lines: two random points on four sides connect the lines (two points are not on the same side) // --- The upper edge 1 (x = 0 ~ width, y = 0) // --- 2 on the right side (x = width, y = 0 ~ height) // --- The following 3 (x = 0 ~ width, y = height) // --- Left side 4 (x = 0, y = 0 ~ height) // Generate random number of lines Integer num = (1, 5); for (Integer i = 0; i < num; i++) { // Set random brush colors (getRandomColor()); // Get two random edges int e1 = 0; int e2 = 0; Set<Integer> edges = (1, 4, 2); for (Integer edge : edges) { // If e1 and e2 have all been assigned, exit the loop and execute it down if (e1 > 0 && e2 > 0) { break; } // If e1 has no assignment, assign the current value to e1 if (e1 == 0) { e1 = edge; // Exit the current loop and execute the next loop continue; } // If e2 has not assigned a value, assign the current value to e2 if (e2 == 0) { e2 = edge; // The last statement of the loop body does not require continued //continue; } } // Two sides have been determined, generating the starting point and end point int p1_x, p1_y; int p2_x, p2_y; if (e1 > 0 && e2 > 0) { // Starting point switch (e1) { // The upper edge (x = 0 ~ width, y = 0) case 1: p1_x = (0, width); p1_y = 0; break; // 2 on the right side (x = width, y = 0 ~ height) case 2: p1_x = width; p1_y = (0, height); break; // The following 3 (x = 0 ~ width, y = height) case 3: p1_x = (0, width); p1_y = height; break; // Left side 4 (x = 0, y = 0 ~ height) default: p1_x = 0; p1_y = (0, height); } // End point switch (e2) { // The upper edge (x = 0 ~ width, y = 0) case 1: p2_x = (0, width); p2_y = 0; break; // 2 on the right side (x = width, y = 0 ~ height) case 2: p2_x = width; p2_y = (0, height); break; // The following 3 (x = 0 ~ width, y = height) case 3: p2_x = (0, width); p2_y = height; break; // Left side 4 (x = 0, y = 0 ~ height) default: p2_x = 0; p2_y = (0, height); } // Draw lines (p1_x, p1_y, p2_x, p2_y); } } return image; } /** * Generate text pictures * * @param text text content * @param fontSize Text size * @return */ @SneakyThrows public static BufferedImage getStringBufferedImage(String text, int fontSize) { int width = () * fontSize + 10; int height = fontSize + 5; // Set width and height, picture type BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); // Get Graphics2D Graphics2D g2d = (); // Create compatible images; Transparency TRANSLUCENT represents image data that contains or may contain any alpha values between 0.0 and 1.0. image = ().createCompatibleImage(width, height, ); // implement (); // Create drawing graphics g2d = (); // Set the drawing area (0, 0, width, height); // Set random brush colors (getRandomColor()); // Set random font style (getRandomFont(fontSize)); // Draw strings (text, 5, height - 5); return image; } /** * Get random colors * * @return */ private static Color getRandomColor() { // Color collection List<Color> colors = new ArrayList<>(); (); (); (); (); (); (); (); return ((0, () - 1)); } /** * Get random fonts * * @param fontSize font size * @return */ private static Font getRandomFont(int fontSize) { // Font name collection List<String> fontNames = new ArrayList<>(); ("Songyi"); ("Microsoft Yahe"); ("Bold"); // Font type collection List<Integer> fontTypes = new ArrayList<>(); // ordinary (); // Bold (); // Italic (); String fontName = ((0, () - 1)); int fontType = ((0, () - 1)); return new Font(fontName, fontType, fontSize); } /** * Determine whether it is a supported image type * @param imageName * @return */ private static boolean isSupportImageType(String imageName){ List<String> imageTypes = new ArrayList<>(); (".jpg"); (".jpeg"); (".gif"); (".png"); String img = (); for (String type : imageTypes) { if((type)){ return true; } } return false; } }
This is the end of this article about Java using Thumbnailator to quickly process images. For more related Java Thumbnailator to process images, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!