java实现图片与base64字符串之间的转换

来源:互联网 发布:淘宝天猫 购物心得 编辑:程序博客网 时间:2024/05/21 14:10
  1. package cn.com;  
  2.   
  3. import <a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. import sun.misc.BASE64Decoder;  
  10. import sun.misc.BASE64Encoder;  
  11.   
  12. public class Base64Test   
  13. {  
  14.     public static void main(String[] args)  
  15.     {  
  16.         String strImg = GetImageStr();  
  17.         System.out.println(strImg);  
  18.         GenerateImage(strImg);  
  19.     }  
  20.     //图片转化成base64字符串  
  21.     public static String GetImageStr()  
  22.     {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理  
  23.         String imgFile = "d://test.jpg";//待处理的图片  
  24.         InputStream in = null;  
  25.         byte[] data = null;  
  26.         //读取图片字节数组  
  27.         try   
  28.         {  
  29.             in = new FileInputStream(imgFile);          
  30.             data = new byte[in.available()];  
  31.             in.read(data);  
  32.             in.close();  
  33.         }   
  34.         catch (IOException e)   
  35.         {  
  36.             e.printStackTrace();  
  37.         }  
  38.         //对字节数组Base64编码  
  39.         BASE64Encoder encoder = new BASE64Encoder();  
  40.         return encoder.encode(data);//返回Base64编码过的字节数组字符串  
  41.     }  
  42.       
  43.     //base64字符串转化成图片  
  44.     public static boolean GenerateImage(String imgStr)  
  45.     {   //对字节数组字符串进行Base64解码并生成图片  
  46.         if (imgStr == null//图像数据为空  
  47.             return false;  
  48.         BASE64Decoder decoder = new BASE64Decoder();  
  49.         try   
  50.         {  
  51.             //Base64解码  
  52.             byte[] b = decoder.decodeBuffer(imgStr);  
  53.             for(int i=0;i<b.length;++i)  
  54.             {  
  55.                 if(b[i]<0)  
  56.                 {//调整异常数据  
  57.                     b[i]+=256;  
  58.                 }  
  59.             }  
  60.             //生成jpeg图片  
  61.             String imgFilePath = "d://222.jpg";//新生成的图片  
  62.             OutputStream out = new FileOutputStream(imgFilePath);      
  63.             out.write(b);  
  64.             out.flush();  
  65.             out.close();  
  66.             return true;  
  67.         }   
  68.         catch (Exception e)   
  69.         {  
  70.             return false;  
  71.         }  
  72.     }  
  73. }  
阅读全文
1 0
原创粉丝点击