admin
2020-03-05 b404321ac200e26fed385eddd6a3deb91a0de174
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package org.yeshi.utils;
 
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
 
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
 
/**
 * 图片裁剪帮助
 * 
 * @author Administrator
 *
 */
public class ImageCropUtil {
 
    /**
     * 剪切图片中间部分(内切)
     * @param sourceImage
     * @param destImage
     * @param ratio
     * @throws FileNotFoundException
     * @throws Exception
     */
    public static void centerCrop(File sourceImage, File destImage, float ratio)
            throws FileNotFoundException, Exception {
        if (!sourceImage.exists())
            throw new FileNotFoundException();
        BufferedImage image = Thumbnails.of(sourceImage).scale(1.0f).asBufferedImage();
        int width = image.getWidth();
        int height = image.getHeight();
        int newWidth = 0;
        int newHeight = 0;
        if (width > ratio * height) {// 以高为主
            newHeight = height;
            newWidth = (int) (newHeight * ratio);
        } else {// 以宽为主
            newWidth = width;
            newHeight = (int) (newWidth / ratio);
        }
 
        if (destImage.exists())
            destImage.delete();
 
        Thumbnails.of(sourceImage).sourceRegion(Positions.CENTER, newWidth, newHeight).scale(1.0)
                .toFile(destImage.getPath());
    }
 
}