用Java写一个方法,传一个图片路径,将图片转为缩略图大小不超过80KB,并将缩略图转为base64字符串返回
时间: 2024-04-14 08:30:03 浏览: 90
java将图片转为base64返回给前端
5星 · 资源好评率100%
可以使用Java的ImageIO和Base64类来实现这个功能。下面是一个示例代码:
```java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Base64;
public class ThumbnailConverter {
public static String convertToThumbnail(String imagePath) {
try {
// 读取原始图片
File imageFile = new File(imagePath);
BufferedImage originalImage = ImageIO.read(imageFile);
// 计算缩略图的尺寸
int targetWidth = 0;
int targetHeight = 0;
double aspectRatio = (double) originalImage.getWidth() / originalImage.getHeight();
if (aspectRatio > 1) {
targetWidth = 80;
targetHeight = (int) (targetWidth / aspectRatio);
} else {
targetHeight = 80;
targetWidth = (int) (targetHeight * aspectRatio);
}
// 创建缩略图
Image thumbnailImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
BufferedImage thumbnailBufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
thumbnailBufferedImage.getGraphics().drawImage(thumbnailImage, 0, 0, null);
// 将缩略图转为base64字符串
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(thumbnailBufferedImage, "jpg", baos);
baos.flush();
byte[] thumbnailBytes = baos.toByteArray();
baos.close();
String base64Thumbnail = Base64.getEncoder().encodeToString(thumbnailBytes);
return base64Thumbnail;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String imagePath = "path/to/image.jpg";
String thumbnailBase64 = convertToThumbnail(imagePath);
System.out.println(thumbnailBase64);
}
}
```
你只需要将`"path/to/image.jpg"`替换为你的图片路径,然后调用`convertToThumbnail`方法即可得到缩略图的base64字符串。请注意,这段代码只能处理JPEG格式的图片,如果有其他格式的图片,请相应地修改代码中的参数。
阅读全文