IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]C#和JAVA实现图片和BASE64互转

    lfsf802发表于 2015-11-29 22:30:03
    love 0
    Base64编码在Web方面有很多应用,譬如在URL、电子邮件方面。有种比较常见的场景就是将图片转换为Base64字符串进行存储。.Net和Java都可以实现此种场景。
    
    .Net Framework也提供了现成的功能类(System.Convert)用于将二进制数据转换为Base64字符串。
    
    将图片转化为Base64字符串的流程是:首先使用BinaryFormatter将图片文件序列化为二进制数据,然后使用Convert类的ToBase64String方法。将Base64字符串转换为图片的流程正好相反:使用Convert类的FromBase64String得到图片文件的二进制数据,然后使用BinaryFormatter反序列化方法。
    
    
    /// <summary> 
        /// 将图片数据转换为Base64字符串 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void ToBase64(object sender, EventArgs e) 
        { 
          Image img = this.pictureBox.Image; 
          BinaryFormatter binFormatter = new BinaryFormatter(); 
          MemoryStream memStream = new MemoryStream(); 
          binFormatter.Serialize(memStream, img); 
          byte[] bytes = memStream.GetBuffer(); 
          string base64 = Convert.ToBase64String(bytes); 
          this.richTextBox.Text = base64; 
        } 
    
        /// <summary> 
        /// 将Base64字符串转换为图片 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void ToImage(object sender, EventArgs e) 
        { 
          string base64 = this.richTextBox.Text; 
          byte[] bytes = Convert.FromBase64String(base64); 
          MemoryStream memStream = new MemoryStream(bytes); 
          BinaryFormatter binFormatter = new BinaryFormatter(); 
          Image img = (Image)binFormatter.Deserialize(memStream); 
          this.pictureBox.Image = img; 
    }
    Java方面实现为:
    需要导入sun.misc.BASE64Decoder.jar包。
    
    实现代码为:
    
    package com.axbsec.util;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import Decoder.BASE64Decoder;
    
    public class StringToImg {
    
        public static final int NUMBER=2833;
    
    
        public static void main(String[] args) {
    
            File fPhotos=new File("C:/Users/Desktop/photos.txt");
    
            File fIDCards=new File("C:/Users /Desktop/idcards.txt");
            BufferedReader reader=null;
            BufferedReader reader1=null;
            String[] fPhotosStr;
            String[] fIDCardsStr;
            try {
                reader=new BufferedReader(new FileReader(fPhotos));
                reader1=new BufferedReader(new FileReader(fIDCards));
    
                fPhotosStr = new String[NUMBER];
                fIDCardsStr = new String[NUMBER];
                String tempString =null;
                String tempString1=null;
                int line=0;
                int line1=0;
    
                while ((tempString=reader.readLine())!=null) {
                    fPhotosStr[line]=tempString;
                    line++;
                }
                reader.close();
    
                while ((tempString1=reader1.readLine())!=null) {
                    fIDCardsStr[line1]=tempString1;
                    line1++;
                }
                reader1.close();
    
                for(int i=0;i<NUMBER;i++){
                    System.out.println("开始导出图片,第"+(i+1)+"张");
                    GenerateImage(fPhotosStr[i],"D:/照片集/"+fIDCardsStr[i]+".jpg");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
        }
    
        // base64字符串转化成图片
        public static boolean GenerateImage(String imgStr,String outputFileName) { // 对字节数组字符串进行Base64解码并生成图片
            if (imgStr == null) // 图像数据为空
                return false;
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                // Base64解码
                byte[] b = decoder.decodeBuffer(imgStr);
                /*for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }*/
                // 生成jpeg图片
                String imgFilePath = outputFileName;// 新生成的图片
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }
    通过这两种平台图片转换为Base64的方法展示,就可以轻易的稍作修改完成将图片存储的业务场景了。
    


沪ICP备19023445号-2号
友情链接