Java利用Base64编码和解码图片文件
1、编码与解码代码如下所示:
1 import java.awt.image.BufferedImage; 2 import java.io.ByteArrayOutputStream; 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.net.MalformedURLException; 7 import java.net.URL; 8 9 import javax.imageio.ImageIO; 10 11 import sun.misc.BASE64Decoder; 12 import sun.misc.BASE64Encoder; 13 14 /** 15 * @author zxn 16 * @version 创建时间:2014-7-2 上午11:40:40 17 * 18 */ 19 public class ImageUtils { 20 /** 21 * 将网络图片进行Base64位编码 22 * 23 * @param imgUrl 24 * 图片的url路径,如http://.....xx.jpg 25 * @return 26 */ 27 public static String encodeImgageToBase64(URL imageUrl) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 28 ByteArrayOutputStream outputStream = null; 29 try { 30 BufferedImage bufferedImage = ImageIO.read(imageUrl); 31 outputStream = new ByteArrayOutputStream(); 32 ImageIO.write(bufferedImage, "jpg", outputStream); 33 } catch (MalformedURLException e1) { 34 e1.printStackTrace(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 // 对字节数组Base64编码 39 BASE64Encoder encoder = new BASE64Encoder(); 40 return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串 41 } 42 43 /** 44 * 将本地图片进行Base64位编码 45 * 46 * @param imgUrl 47 * 图片的url路径,如http://.....xx.jpg 48 * @return 49 */ 50 public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 51 ByteArrayOutputStream outputStream = null; 52 try { 53 BufferedImage bufferedImage = ImageIO.read(imageFile); 54 outputStream = new ByteArrayOutputStream(); 55 ImageIO.write(bufferedImage, "jpg", outputStream); 56 } catch (MalformedURLException e1) { 57 e1.printStackTrace(); 58 } catch (IOException e) { 59 e.printStackTrace(); 60 } 61 // 对字节数组Base64编码 62 BASE64Encoder encoder = new BASE64Encoder(); 63 return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串 64 } 65 66 /** 67 * 将Base64位编码的图片进行解码,并保存到指定目录 68 * 69 * @param base64 70 * base64编码的图片信息 71 * @return 72 */ 73 public static void decodeBase64ToImage(String base64, String path, 74 String imgName) { 75 BASE64Decoder decoder = new BASE64Decoder(); 76 try { 77 FileOutputStream write = new FileOutputStream(new File(path 78 + imgName)); 79 byte[] decoderBytes = decoder.decodeBuffer(base64); 80 write.write(decoderBytes); 81 write.close(); 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } 85 } 86 } 87
2、直接在页面上显示base64编码的图片
1 <html> 2 <body> 3 <img src='data:image/jpg;base64,base64码'/> 4 5 </body> 6 </html>