zoukankan      html  css  js  c++  java
  • Android中Base64的简单使用

     1 服务端图片的信息被转化成字符串,传到android客户端,android端需要把这些信息再解码转化成图片并保存在本地。
     2 //编码部分
     3 String string = Base64.encodeToString(str.getBytes(),Base64.DEFAULT);
     4    //解码部分string 是服务端发来的信息
     5 byte[] byteIcon= Base64.decode(string,Base64.DEFAULT);
     6 for (int i = 0; i < byteIcon.length; ++i) {  
     7     if (byteIcon[i] < 0) {  
     8 byteIcon[i] += 256;  
     9  }}  
    10 //建立一个文件对象
    11 File iconFile = new File("userIcon.png");
    12 FileOutputStream fos = new FileOutputStream(iconFile);
    13 if(!iconFile.exists())
    14 {
    15  iconFile.creatNewFile();    
    16 }
    17 //把图片数据写入文件形成图片
    18 fos.write(byteIcon);
    19 
    20 我到网上搜了一下,发现我这种写法变复杂了,实际上byteIcon可以直接转换成Bitmap,不过这样就不能实现本地保存了
    21 //服务端
    22 //编码,记住这个流,经常用于图片和Base64数据的切换
    23 ByteArrayOutputStream baos = new ByteArrayOutputStream();
    24 //图片压缩并转换成流,bitmap在这我就不初始化了
    25 bitmap.compress(Bitmap.compressFormat,100,baos);
    26 byte[] byteServer = baos.toByteArray();
    27 String result = Base64.encodeToString(byteServer.Base64.DEFAULT);
    28 [在此输入链接描述][1]
    29 
    30 //android端
    31 byte[] byteIcon = Base64.decode(result,Base64.DEFAULT);
    32 Bitmap bitmap = BitmapFactory.decode(byteIcon,0,byteIcon.length);

    以上数据转自:http://my.oschina.net/lengwei/blog/355901仅作为收藏,

    在我自己的一篇文章里面也是用到了Base64,有兴趣的可以去看看,http://www.cnblogs.com/fuck1/p/5459660.html

  • 相关阅读:
    JS对象—对象总结(创建、属性、方法)
    总结30个css选择器
    null、undefined、typeof、instanceof
    Hybrid App 原理解析
    promise与async-await
    你不知道的javascript
    Function.prototype.toString 的使用技巧
    Javascript中的valueOf与toString
    HTML5 Page Visibility
    深入理解css3中 nth-child 和 nth-of-type 的区别
  • 原文地址:https://www.cnblogs.com/fuck1/p/5459685.html
Copyright © 2011-2022 走看看