Android中对图像进行Base64编码

首先我们来看看维基百科是怎么定义的这个概念的。

Base64 is a generic term for a number of similar encoding schemes that encode binary data by treating it numerically and translating it into a base 64 representation. The Base64 term originates from a specificMIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML.

当然我们对于概念可以不做过多的理会,只要知道这是一种编码方式,设计用来进行数据传输,而且要不易为人读懂,也就是为了加密用的设计的目的是用文本字符串来传输二进制数据(经麦壳童鞋和KongQue童鞋二人提醒后,更正)。至于他的算法实现,我们可以Google出来很多中成熟的算法。

我选用了这个网站上提供的源码,测试之后暂时还没有发现问题,并且该源码的作者将版权完全放弃了,无需任何的License授权,也不怕License感染,拿过来用就是了,作者只是希望使用的人如果发现问题可以反馈给他,如果能参与进来一起解决那是更好。

Android SDK2.2之后提供了Base64编码相关的API类Base64,不过鉴于开发的程序需要向下兼容,我想大部分的程序还是需要自己实现或者寻求第三方的实现来解决该问题。下面我们来一步步看看如何将图片编码成一个Base64编码的字符串进行传输。

任何图像到了程序中都需要解码成为Bitmap来进行绘制(不论是显示的解码还是系统在API中帮的忙),解码之后的Bitmap就是一张位图也就是一个byte数组,在Android中Bitmap有compress(Bitmap.CompressFormat format, int quality, OutputStream stream)这个方法,该方法可以将Bitmap重新压缩存储为别的格式,可以是PNG/JPG文件,或者是ByteArrayOutputStream输出。

public static String getBitmapStrBase64(Bitmap bitmap){
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bitmap.compress(CompressFormat.PNG, 100, baos);
    byte[] bytes  = baos.toByteArray();
    return Base64.encodeBytes(bytes);
}

这就是获取位图Base64编码的代码,同理也可以将Base64编码字符串转化为Bitmap对象

public Bitmap getBitmap(){
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(iconBase64);
            return BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

以上就是所有的代码实现了,比较简单,效率还不错。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据