【其他图片格式转JPEG格式base64】

本文介绍了一个用于将不同格式图片转换为JPEG格式的工具类。该工具通过使用thumbnailator库实现,能够处理base64编码的图片,并将其转换为JPEG格式后再进行base64编码输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 背景

用户上传图片,对图片做特征提取,而特征提取服务只支持JPEG格式的base64 ,这就需要我们先把图片格式转为JPEG 格式

2. 转换工具类

2.1 引入依赖

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

2.3 转换方法

public static String base64Handle2Jpeg(String base64Src) {
        //判断是否包含 data:image/png,base64字符串 等头信息
		int index = base64Src.indexOf(",");
		String base64Str = base64Src;
		if (index > 0) {
			base64Str = base64Src.substring(index + 1);//去除头信息
			try {
				BufferedImage bufferedImage = base64String2BufferedImage(base64Str);
				int width = bufferedImage.getWidth();
				int height = bufferedImage.getHeight();
				
				String filePath = "/tmp/"+System.currentTimeMillis()+".jpeg"; //存入临时文件 
				Thumbnails.of(bufferedImage)
				.size(width, height)
                .outputFormat("jpeg")
                .toFile(filePath);
				
                String result = imageToBase64Str(filePath); //转base64
                FileUtils.deleteQuietly(new File(filePath)); //删除临时文件
                return result; //返回结果
			} catch (Exception e) {
                e.printStackTrace();
			}
		}

		return null;
	}
     public static String imageToBase64Str(String imgFile) throws Exception{
	    byte[] bytes = FileUtils.readFileToByteArray(new File(imgFile));
		// 加密
		return EncodeUtil.encodeBase64(bytes);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang_xiaoxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值