zoukankan      html  css  js  c++  java
  • Android Drawable 和String 相互转化

    在我们经常应用开发中,经常用到将drawable和string相互转化。注意这情况最好用于小图片入icon等。

     

    [java] view plain copy
     
    1. public synchronized Drawable byteToDrawable(String icon) {    
    2.          
    3.         byte[] img=Base64.decode(icon.getBytes(), Base64.DEFAULT);  
    4.         Bitmap bitmap;    
    5.         if (img != null) {    
    6.     
    7.                 
    8.             bitmap = BitmapFactory.decodeByteArray(img,0, img.length);    
    9.             @SuppressWarnings("deprecation")  
    10.             Drawable drawable = new BitmapDrawable(bitmap);    
    11.                 
    12.             return drawable;    
    13.         }    
    14.         return null;    
    15.     
    16.     }  
    17.     public  synchronized  String drawableToByte(Drawable drawable) {    
    18.           
    19.         if (drawable != null) {    
    20.             Bitmap bitmap = Bitmap    
    21.                     .createBitmap(    
    22.                             drawable.getIntrinsicWidth(),    
    23.                             drawable.getIntrinsicHeight(),    
    24.                             drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888    
    25.                                     : Bitmap.Config.RGB_565);    
    26.             Canvas canvas = new Canvas(bitmap);    
    27.             drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),    
    28.                     drawable.getIntrinsicHeight());    
    29.             drawable.draw(canvas);    
    30.             int size = bitmap.getWidth() * bitmap.getHeight() * 4;    
    31.             
    32.             // 创建一个字节数组输出流,流的大小为size    
    33.             ByteArrayOutputStream baos = new ByteArrayOutputStream(size);    
    34.             // 设置位图的压缩格式,质量为100%,并放入字节数组输出流中    
    35.             bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);    
    36.             // 将字节数组输出流转化为字节数组byte[]    
    37.             byte[] imagedata = baos.toByteArray();    
    38.               
    39.            String icon= Base64.encodeToString(imagedata, Base64.DEFAULT);  
    40.             return icon;    
    41.         }    
    42.         return null;    
    43.     } 
  • 相关阅读:
    Aix_bugzilla
    aix Mysql安装 Oracle官方教程
    Aix6.1安装openssh
    日媒:阿里巴巴上市融资或超Facebook
    设计模式(一)---单例模式
    Handler具体解释系列(七)——Activity.runOnUiThread()方法具体解释
    TCP/IP协议族——IP工作原理及实例具体解释(上)
    leetCode 41.First Missing Positive (第一个丢失的正数) 解题思路和方法
    Material Design之RecyclerView的使用(一)
    jQuery和CSS3超酷表单美化插件
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/5629727.html
Copyright © 2011-2022 走看看