引言

图片处理库选择

添加依赖

在使用Thumbnailator之前,需要将其添加到项目的依赖中。以下是一个Maven依赖示例:

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

获取图片尺寸

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;

public class ImageSizeExample {
    public static void main(String[] args) {
        try {
            File originalImage = new File("path/to/your/image.jpg");
            int width = Thumbnails.of(originalImage).getWidth();
            int height = Thumbnails.of(originalImage).getHeight();
            System.out.println("Width: " + width + " Height: " + height);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

调整图片尺寸

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;

public class ImageResizeExample {
    public static void main(String[] args) {
        try {
            File originalImage = new File("path/to/your/image.jpg");
            File resizedImage = new File("path/to/your/resized_image.jpg");
            Thumbnails.of(originalImage)
                    .scale(0.5f) // 设置缩放比例,0.5表示缩小到原来的一半
                    .toFile(resizedImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

调整图片比例

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;

public class ImageAspectExample {
    public static void main(String[] args) {
        try {
            File originalImage = new File("path/to/your/image.jpg");
            File aspectImage = new File("path/to/your/aspect_image.jpg");
            Thumbnails.of(originalImage)
                    .size(800, 600) // 设置新的尺寸
                    .keepAspectRatio(false) // 不保持原始比例
                    .toFile(aspectImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

结论