SpringBoot系列13-整合thumbnailator将图片文件压缩转换成base64字符串

猿份哥 18天前 ⋅ 53 阅读

一.Thumbnails用法介绍:

1.按指定大小把图片进行缩和放(会遵循原图高宽比例)

//此处把图片压成400×500的缩略图
//变为400*300,遵循原图比例缩或放到400*某个高度
Thumbnails.of(fromPic).size(400,500).toFile(toPic);

//按照比例进行缩小和放大
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小

Thumbnails.of(fromPic).scale(2f);//按比例放大

//不按比例,就按指定的大小进行缩放
Thumbnails.of(fromPic).size(100, 100).keepAspectRatio(false).toFile(toPic);
//或者
Thumbnails.of(fromPic).forceSize(100,100).toFile(toPic);

2.旋转图片

rotate(角度),正数则为顺时针,负数则为逆时针

Thumbnails.of(fromPic).size(200,200).rotate(90).toFile(toPic);

3.图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量

Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

4.给图片加水印,watermark(位置,水印图,透明度)Positions.CENTER表示加在中间

Thumbnails.of(fromPic).size(400,400)
        .watermark(Positions.CENTER,ImageIO.read(waterPic),0.5f)
        .outputQuality(0.8f).toFile(toPic);

5.用sourceRegion()实现图片裁剪

//图片中心300*300的区域,Positions.CENTER表示中心,还有许多其他位置可选
Thumbnails.of(fromPic).sourceRegion(Positions.CENTER,300,300)
        .size(300,300).toFile(toPic);
//图片中上区域300*300的区域
Thumbnails.of(fromPic).sourceRegion(Positions.TOP_CENTER,300,300)
        .size(300,300).toFile(toPic);
Thumbnails.of(fromPic).sourceRegion(0,0,200,200)
        .size(300,300).toFile(toPic);

以上资料摘自:https://www.cnblogs.com/ryan304/p/9546670.html

二开始实操:将图片文件使用Thumbnails图片压缩处理后转换为base64字符串

1.添加maven依赖:

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

编写工具类

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/04 18:37
 */
public class ImageUtils {

    private static String ImageFormat="jpg";


    /**
     * 按照比例和规格压缩图片得到base64图片字符串
     * @param maxSize 单位kb
     * @param w
     * @param h
     * @return
     */
    public static String resizeImage(String filePath,int maxSize,int w,int h){
        try {
            BufferedImage src = fileToBufferedImage(filePath);
            BufferedImage output = Thumbnails.of(src).size(w, h).asBufferedImage();
            String base64 = imageToBase64(output);
            while (base64.length() - base64.length() / 8 * 2 > maxSize*1000) {
                output = Thumbnails.of(output).scale(0.9f).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return imageToBase64(output);
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }


    /**
     * 图片文件转BufferedImage
     * @param filePath
     * @return
     * @throws Exception
     */
    public static BufferedImage fileToBufferedImage(String filePath) throws Exception{
        FileInputStream is=new FileInputStream(filePath);
        BufferedImage img = ImageIO.read(is);
        return  img;
    }

    /**
     * 将图片base64字符串转换为BufferedImage
     * @param base64string
     * @return
     */
    public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {
            InputStream stream = base64StringToInputStream(base64string);
            image = ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 将base64字符转换为输入流
     * @param base64string
     * @return
     */
    private static InputStream base64StringToInputStream(String base64string) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64string.getBytes());
        InputStream inputStream=byteArrayInputStream;
        return inputStream;
    }

    /**
     * 将BufferedImage转换为base64字符串
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, ImageFormat, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

}

resizeImage方法使用while循环将图片大小于压缩到指定的大小后不再压缩。

编写测试类

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/04 16:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ImageTest {

	@Test
	public void imageFileToBase64() throws Exception {
		String filePath="D:\\data\\test\\0.jpg";
		String imageStr = ImageUtils.resizeImage(filePath, 60, 300, 420);
		System.out.println(imageStr);
	}
	
}

最后猿份哥双手给大家奉上代码地址,希望大家喜欢

https://github.com/tiankonglanlande/springboot/tree/master/springboot-thumbnailator-base64


全部评论: 0

    我有话说: