今天做项目,用到android.util.Base64这个类来把 byte[] 数组转换为 base64-encode 的String类型


static String

encodeToString(byte[] input, int offset, int len, int flags)
Base64-encode the given data and return a newly allocated String with the result.


而这个byte[]我是从一张图片的bitmap转化而来的:

具体转换代码如下:

/**
 *
 * @file BitmapToBytesUtil.java
 * @author Samuel.Cai
 * @date Jan 6, 2012
 */
public class BitmapToBytesUtil {
    public static byte[] bitmapToBytes(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        return os.toByteArray();
    }
}


一开始使用的是:

 new String(Base64.decode(BitmapToBytesUtil.bitmapToBytes(bitmap), Base64.DEFAULT));  这样写后,运行程序得到的结果是crash

:


01-06 15:28:09.616: E/AndroidRuntime(776): Caused by: java.lang.IllegalArgumentException: bad base-64
01-06 15:28:09.616: E/AndroidRuntime(776):     at android.util.Base64.decode(Base64.java:161)
01-06 15:28:09.616: E/AndroidRuntime(776):     at android.util.Base64.decode(Base64.java:136)


解决方法:

换一种写法就ok了:

Base64.encodeToString(BitmapToBytesUtil.bitmapToBytes(bitmap), Base64.DEFAULT)

错误原因:英文太烂,加密与解密分辨不清

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐