java将图片转成base64
时间: 2024-05-23 20:08:04 浏览: 140
Java可以将图片转成base64字符串的方法主要有两种:
1.使用Java自带的Base64类
```
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
public class ImageToBase64 {
public static void main(String[] args) {
String base64Str = null;
InputStream in = null;
try {
in = new FileInputStream("image.jpg");
byte[] bytes = new byte[in.available()];
in.read(bytes);
base64Str = Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(base64Str);
}
}
```
2.使用第三方库Apache Commons Codec
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
public class ImageToBase64 {
public static void main(String[] args) {
String base64Str = null;
FileInputStream fileInputStreamReader = null;
try {
File file = new File("image.jpg");
byte[] bytes = new byte[(int) file.length()];
fileInputStreamReader = new FileInputStream(file);
fileInputStreamReader.read(bytes);
base64Str = new String(Base64.encodeBase64(bytes), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(base64Str);
}
}
```
阅读全文