图片转Base64换行的问题

接上一篇 Android识别手写笔迹并透明化处理

由于我们的服务端接口是通过base64接收处理后的图片,因此需要将图片处理成Base64字符串(忽略将图片从文件转化为Bitmap的过程)

/**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
    
    
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
    
    
            if (bitmap != null) {
    
    
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (baos != null) {
    
    
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return result;
    }

产生问题

base64的字符串中每76个字符后面会被添加上一个\n符号

产生原因

我们采用的是Base64.DEFAULT的flags进行转码,会造成字符串中有很多\n分隔符,原因是由于RFC2045规范每行字符串不能超过76个字符,因此Base64在编码的时候会添加\n分隔符,此规范链接RFC2045规范
在这里插入图片描述
此问题会导致我们给服务端提交base64的时候,该图片在web上无法通过 src='data:image/jpeg;base64,...'正常展示图片

解决方法

将flags设置为Base64.NO_WRAP,在Android的文档中有说明,设置为这个flag,则返回的字符串将会一个长串(也就是不会换行),这正是我们期望的结果

// 	NO_WRAP
// Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).
result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);

猜你喜欢

转载自blog.csdn.net/u010899138/article/details/110647056