2

我想将base64编码的图片从ruby on rails发送到android。将数据发送到rails包括图片编码和解码工作,从rails传回android的数据也可以,但是我无法解码由rails编码的图片。我总是在以下标记行收到 NullpointerException:

imageOutFile = new FileOutputStream(file);
byte[] bytes = Base64.decode(imageString, Base64.URL_SAFE);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
**bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOutFile);**

编码后的字符串如下所示(它是最短的):

_9j_4AAQSkZJRgABAQEASABIAAD_4Se-RXhpZgAASUkqAAgAAAALAA4BAgAUAAAAkgAAAA8BAgAUAAAApgAAABABAgAJAAAAugAAABIBAwABAAAAAQAAAA==

另一个字符串是这样的:

_9j_4AAQSkZJRgABAQEAAQABAAD_2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH_2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH_wAARCAHgAoADASIAAhEBAxEB_8QAHAABAQEBAQEBAQEAAAAAAAAAAAoICQcGAgED_8QARRAAAQIBCAYIBAQEBwACAwAAAAYHBQEECAkZOIe3AxQVFqfWAhhWV1iWl9cXaNXnERIjJRM2VfAkJic1UZSkUmchMjf_xAAXAQEBAQEAAAAAAAAAAAAAAAAACQEH_8QAMxEBAAAEAwUGBQMFAAAAAAAAAAEGB1YCGJYDcbHV1ggXQUam8AURFjFRYaG1IYGRxcb_2gAMAwEAAhEDEQA_AIPwAAAAAAACo6rguPM3iPm-vCXEqOq4LjzN4j5vrwDbQAAAAAAABLnWM33Hqw4yoQ5UYS51jN9x6sOMqEOBiMAAAAAAAAqOq4LjzN4j5vrwlxKjquC48zeI-b68A20AAAAAAAAS51jN9x6sOMqEOVGEudYzfcerDjKhDgYjAAAAAAAAKjquC48zeI-b68JcSo6rguPM3iPm-vANtAAAAAAAAEudYzfcerDjKhDlRhLnWM33Hqw4yoQ4GIwAAAAAAACo6rguPM3iPm-vCXEqOq4LjzN4j5vrwDbQAAAAAAABLnWM33Hqw4yoQ5UYS51jN9x6sOMqEOBiMAAAAAAAAqOq4LjzN4j5vrwlxKjquC48zeI-b68A20AAAAAAAAS51jN9x6sOMqEOVGEudYzfcerDjKhDgbYsbvmb4PfdIWN3zN8HvukdtABxLsbvmb4PfdIWN3zN8HvukdtABxLsbvmb4PfdIWN3zN8HvukdtABxLsbvmb4PfdId

在 Logcat 中,解码失败后,我收到这样的消息:

--- decoder->decode returned false

我使用以下方法对字符串进行编码,并将带有 json 对象的字符串发送到 android。图片是用 CarrierWave 的上传者上传的。

Base64.urlsafe_encode64(File.read("public#{picture_path.to_s}"))
4

1 回答 1

2

我必须读取文件二进制文件(“rb”),然后对其进行编码。

Base64.encode64(File.open("public#{picture_path.to_s}", "rb") {|io| io.read})
于 2013-08-08T19:46:36.407 回答