我想从rails上的ruby发送base64编码的图片到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}"))
答案 0 :(得分:2)
我必须读取文件二进制文件(“rb”)然后对其进行编码。
Base64.encode64(File.open("public#{picture_path.to_s}", "rb") {|io| io.read})