Java base64图片 width height
时间: 2023-12-01 13:43:22 浏览: 121
可以使用Java的ImageIO类和Base64类来获取图片的宽度和高度,并将图片转换为Base64格式。以下是一个示例代码:
```java
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;
public class ImageUtils {
public static String getImageBase64(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(bytes);
}
public static int[] getImageSize(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
return new int[]{width, height};
}
}
```
使用该类的getImageBase64方法可以将图片转换为Base64格式,getImageSize方法可以获取图片的宽度和高度。例如:
```java
File file = new File("image.jpg");
String base64 = ImageUtils.getImageBase64(file);
int[] size = ImageUtils.getImageSize(file);
System.out.println("Base64: " + base64);
System.out.println("Width: " + size[0]);
System.out.println("Height: " + size[1]);
```
阅读全文