public class EncodeBase64 {
/**
* 将本地图片进行Base64位编码
*
* @param ,如http://.....xx.jpg
* @return
*/
public static String encodeImgageToBase64Jpg(File imageFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
return new String(Base64.encode(outputStream.toByteArray()));// 返回Base64编码过的字节数组字符串
}
public static String encodeImgageToBase64Png(File imageFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
return new String(Base64.encode(outputStream.toByteArray()));// 返回Base64编码过的字节数组字符串
}
public static String encodeImgageToBase64(File imageFile, String imageType) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imageType, outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
return new String(Base64.encode(outputStream.toByteArray()));// 返回Base64编码过的字节数组字符串
}
/**
* writeFile.
*
* @param fullFileName file path
* @param contents contents
*/
public static void writeFile(final String fullFileName, final byte[] contents) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(fullFileName, "rw");
raf.seek(raf.length());
try (FileChannel channel = raf.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(contents.length);
buffer.put(contents);
buffer.flip();
while (buffer.hasRemaining()) {
channel.write(buffer);
}
channel.force(true);
}
} catch (IOException e) {
e.printStackTrace();
} finally { // add by eddy
if (null != raf) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
图片转为base64位数据方法类
最新推荐文章于 2024-04-18 08:18:26 发布