图片转化成base64字符串

来源:互联网 发布:js object添加元素 编辑:程序博客网 时间:2024/05/16 01:27
  1. import java.io.FileInputStream;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import sun.misc.BASE64Decoder;  
  7. import sun.misc.BASE64Encoder;  
  8.   
  9. public class Base64 {  
  10.   
  11.     // 图片转化成base64字符串  
  12.     public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理  
  13.         InputStream in = null;  
  14.         byte[] data = null;  
  15.         // 读取图片字节数组  
  16.         try {  
  17.             if(imgFile==null||"".equals(imgFile)){  
  18.                 imgFile="uploaddir/file/default.png";  
  19.             }  
  20.             in = new FileInputStream(imgFile);  
  21.             data = new byte[in.available()];  
  22.             in.read(data);  
  23.             in.close();  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.         // 对字节数组Base64编码  
  28.         BASE64Encoder encoder = new BASE64Encoder();  
  29.         return encoder.encode(data);// 返回Base64编码过的字节数组字符串  
  30.     }  
  31.   
  32.     // base64字符串转化成图片  
  33.     public static boolean GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片  
  34.         if (imgStr == null// 图像数据为空  
  35.             return false;  
  36.         BASE64Decoder decoder = new BASE64Decoder();  
  37.         try {  
  38.             // Base64解码  
  39.             byte[] b = decoder.decodeBuffer(imgStr);  
  40.             for (int i = 0; i < b.length; ++i) {  
  41.                 if (b[i] < 0) {// 调整异常数据  
  42.                     b[i] += 256;  
  43.                 }  
  44.             }  
  45.             // 生成jpeg图片  
  46.             String imgFilePath = "d://222.jpg";// 新生成的图片  
  47.             OutputStream out = new FileOutputStream(imgFilePath);  
  48.             out.write(b);  
  49.             out.flush();  
  50.             out.close();  
  51.             return true;  
  52.         } catch (Exception e) {  
  53.             return false;  
  54.         }  
  55.     }  
  56.   

原创粉丝点击