修改上面方法,改为可以处理所有格式的图片
时间: 2024-04-19 13:28:15 浏览: 95
Android 图片的颜色处理实例代码
要处理所有格式的图片,你可以使用 `javax.imageio.ImageIO` 的 `write` 方法,并将输出流转换为字节数组。下面是修改后的代码:
```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, getImageFormat(imagePath), baos);
baos.flush();
byte[] thumbnailBytes = baos.toByteArray();
baos.close();
String base64Thumbnail = Base64.getEncoder().encodeToString(thumbnailBytes);
return base64Thumbnail;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String getImageFormat(String imagePath) {
int dotIndex = imagePath.lastIndexOf(".");
if (dotIndex != -1 && dotIndex < imagePath.length() - 1) {
return imagePath.substring(dotIndex + 1).toLowerCase();
}
return "jpg"; // 默认为JPEG格式
}
public static void main(String[] args) {
String imagePath = "path/to/image.jpg";
String thumbnailBase64 = convertToThumbnail(imagePath);
System.out.println(thumbnailBase64);
}
}
```
这段代码中,我添加了 `getImageFormat` 方法来获取图片的格式。它通过从文件路径中提取最后一个点号之后的字符串来获取格式。如果无法提取格式,则默认为JPEG格式。这样,无论图片是什么格式,都可以正确处理并转换为缩略图的base64字符串。记得将 `"path/to/image.jpg"` 替换为你的实际图片路径。
阅读全文