为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Base64 将图库照片转换为 BASE64 时获取损坏的图像字符串。

使用 Base64 将图库照片转换为 BASE64 时获取损坏的图像字符串。

慕桂英3389331 2022-09-21 16:56:09
使用 Base64 编码器从活动转换图库照片时,我得到一个错误的 Base64 字符串。当使用网站对此进行测试时,它是一个损坏的图像。我的 ExpressAPI 在尝试发布此字符串时,也会对字符串给出验证错误。我已经尝试过使用不同的位图变体,如工厂等。@Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        //call super        super.onActivityResult(requestCode, resultCode, data);        Uri imageUri = data.getData();        InputStream imageStream = null;        try {            imageStream = getContentResolver().openInputStream(imageUri);        } catch (FileNotFoundException e) {            e.printStackTrace();        }        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);        encodedString = encodeImage(selectedImage);    } private String encodeImage(Bitmap bm)    {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);        byte[] b = baos.toByteArray();        String encImage = Base64.encodeToString(b, Base64.DEFAULT);        Log.d(encImage, "Image:");        return encImage;    }
查看完整描述

4 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

Java 在 base64 字符串中使用空格对位图进行解码,请尝试以下操作:encodedString.replaceAll("\\s+","");



查看完整回答
反对 回复 2022-09-21
?
临摹微笑

TA贡献1982条经验 获得超2个赞

试试这个:


public String encodeTobase64(Bitmap image) {

    Bitmap immagex=image;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);

    byte[] b = baos.toByteArray();

    String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);


    Log.e("EncodedImage: ", imageEncoded);

    return imageEncoded;

}

在活动结果() 中使用下面的代码


InputStream imageStream = null;

        try {

            imageStream = this.getContentResolver().openInputStream(selectedImage);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        }

        Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);

        encodeTobase64(yourSelectedImage);


查看完整回答
反对 回复 2022-09-21
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您可以尝试通过您选择的文件的路径来获取位图:


在您的 onActivity结果


Uri targetUri = data.getData();

String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(targetUri,

    filePathColumn, null, null, null);

cursor.moveToFirst();


int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

//getting the actual path of the file

String path = cursor.getString(columnIndex);

cursor.close();


Bitmap bm = BitmapFactory.decodeFile(path);


//your encoding function is ok

encodedString = encodeImage(selectedImage);


查看完整回答
反对 回复 2022-09-21
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

右。。我已经找到了答案。基本上,Android认为在我的字符串中插入多个空格很有趣。

通过执行此操作,您可以将其全部删除:

activity.getEncodedString().replaceAll("\s+","")


查看完整回答
反对 回复 2022-09-21
  • 4 回答
  • 0 关注
  • 172 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信