import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* ImageBase64轉換類
* @author admin
*/
public class ImageBase64Utils {
/**
* 將網絡圖片進行Base64位編碼
* @param imageUrl 圖片的url路徑,如http://.....xx.jpg
* @return
*/
public static String encodeImgageToBase64(String imageUrl) {
// 將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64編碼過的字節數組字符串
return encoder.encode(outputStream.toByteArray());
}
/**
* 將本地圖片進行Base64位編碼
*/
public static String encodeImgageToBase64(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編碼
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64編碼過的字節數組字符串
return encoder.encode(outputStream.toByteArray());
}
/**
* 將Base64位編碼進行轉本地圖片
*/
public static void decodeBase64ToImage(String base64, String path,String imgName) {
BASE64Decoder decoder = new BASE64Decoder();
try {
FileOutputStream write = new FileOutputStream(new File(path
+ imgName));
byte[] decoderBytes = decoder.decodeBuffer(base64);
write.write(decoderBytes);
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}