如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串

Posted

技术标签:

【中文标题】如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串【英文标题】:How to convert byte array of an image to a base64 encoded string representing a jpg 【发布时间】:2015-08-21 02:16:36 【问题描述】:

我正在编写一个拍摄照片并上传照片的 android 应用。

API 需要一个表示要上传的 jpg 的 base 64 编码字符串。

Camera API 给了我一个byte []

如何将此字节数组转换为 base64 编码字符串,以确保保持 jpg 格式?

目前,我正在尝试String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);

但这不知何故是无效的,在日志中给了我一堆AAAAAAAAAs,而不是真正的base64编码字符串。

感谢您的帮助

编辑:

其实,当我退出上面encoded的内容时,我得到了

 /9j/4UVIRXhpZgAATU0AKgAAAAgACQEPAAIAAAAPAAAAegEQAAIAAAAJAAAAigESAAMAAAABAAEAAAEaAAUAAAABAAAAlAEbAAUAAAABAAAAnAEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAApIglAAQAAAABAAAGCAAABi5MRyBFbGVjdHJvbmljcwAAVlM5ODUgNEcAAAAAAEgAAAABAAAASAAAAAEAFIKaAAUAAAABAAABmoKdAAUAAAABAAABoognAAMAAAABAGQAAJAAAAcAAAAEMDIyMJADAAIAAAAUAAABqpAEAAIAAAAUAAABvpEBAAcAAAAEAQIDAJIEAAoAAAABAAAB0pIHAAMAAAABAAIAAJIJAAMAAAABAAAAAJIKAAUAAAABAAAB2pJ8AAcAAAIAAAAB4pKGAAcAAAIAAAAD4qAAAAcAAAAEMDEwMKABAAMAAAABAAEAAKACAAQAAAABAAAFAKADAAQAAAABAAADwKAFAAQAAAABAAAF6qQDAAMAAAABAAAAAKQEAAUAAAABAAAF4gAAAAAAAAABAAAAGAAAAMgAAABkMjAxNTowNjowNSAyMjoxMzoxOAAyMDE1OjA2OjA1IDIyOjEzOjE4AAAAAAAAAAABAAAHCAAAA+hBTENTSUlGMFUAAAAAAAAAAQAPJ3ECAA0UIBAHEhUAAEl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AYDR1E0dXCPaoXHtWpzoytVQf2fJ7AH9a58qAK6XU1zp0/+4a51h8ufSuav0OvD7MUL+5XjuRSxkB04pV5hHsaBgMp5rGHxI3lsbqqrIMgHimvbRMOUFTIMxr9Kdtr0rI47sxr23jiKlOOelERZo8lcH61b1GP5EPvV

但是当它实际发布到服务器时(使用 Square 的 Retrofit 库),我会收到数十万个 AAAAAs,这会破坏服务器。

尽管如此,但记录的编码字符串似乎不够长,无法封装与 LG G3 中的照片相关的所有数据。

【问题讨论】:

Base64.encodeBase64(byteArray).toString()? 您尝试以哪种格式保存在服务器上???????? 【参考方案1】:

使用

byte [] data = Base64.decode(base64str);

您需要在项目中引用 commons codec 才能使该代码正常工作。

【讨论】:

以上是关于如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串的主要内容,如果未能解决你的问题,请参考以下文章

将字节数组转换/显示为 bmp/jpeg 图像

将图像读取到字节数组并更改它

如何将字节数组作为图像文件存储在磁盘上?

如何将 int[] 转换为 byte[]

如何仅使用 javascript 将图像转换为字节数组以将图像存储在 sql server 上?

如何将UIImagePicker图像转换为字节数组objective-c