2

我有一个 Base64 编码的图像字符串驻留在文件服务器中。编码的字符串有一个前缀(例如:“data:image/png;base64”),以支持流行的现代浏览器(它是通过 JavaScript 的Canvas.toDataURL() 方法获得的)。客户端向我的服务器发送图像请求,服务器对其进行验证并返回 Base64 编码字符串的流。

如果客户端是 Web 客户端,则可以通过将 设置为 Base64 编码字符串来在<img>标签内按原样显示图像。src但是,如果客户端是Android客户端,则需要将String解码成不带前缀的Bitmap。不过,这可以相当容易地完成。

问题: 为了简化我的代码而不是重新发明轮子,我使用 Android 客户端的图像库来处理加载、显示和缓存图像(确切地说是Facebook 的Fresco 库)。但是,似乎没有库支持 Base64 解码(我也想要我的蛋糕并吃掉它)。我想出的一个解决方案是在服务器上解码 Base64 字符串,因为它正在流式传输到客户端。

尝试:

S3Object obj = s3Client.getObject(new GetObjectRequest(bucketName, keyName));
Base64.Decoder decoder = Base64.getDecoder();
//decodes the stream as it is being read
InputStream stream = decoder.wrap(obj.getObjectContent());
try{
    return new StreamingOutput(){
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException{
            int nextByte = 0;
            while((nextByte = stream.read()) != -1){
                output.write(nextByte);
            }
            output.flush();
            output.close();
            stream.close();
        }
    };
}catch(Exception e){
    e.printStackTrace();
} 

不幸的是,Fresco 库在显示图像时仍然存在问题(没有堆栈跟踪!)。由于在解码流时我的服务器上似乎没有问题(也没有堆栈跟踪),这让我相信这一定是前缀的问题。这让我进退两难。

问题:如何从发送到客户端的 Stream 中删除 Base64 前缀,而不在服务器上存储和编辑整个 Stream?这可能吗?

4

2 回答 2

0

Fresco 确实支持解码数据 URI,就像 Web 客户端一样。

演示应用程序有一个例子

于 2015-08-24T22:33:17.133 回答
0

如何从发送到客户端的 Stream 中删除 Base64 前缀,而不在服务器上存储和编辑整个 Stream?

在将流发送到客户端时删除前缀是一项非常复杂的任务。如果您不介意将整个字符串存储在服务器上,您可以简单地执行以下操作:

BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
    br = new BufferedReader(new InputStreamReader(stream));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    String result = sb.toString();
    //comma is the charater which seperates the prefix and the Base64 String
    int i = result.indexOf(",");
    result = result.substring(i + 1);
    //Now, that we have just the Base64 encoded String, we can decode it
    Base64.Decoder decoder = Base64.getDecoder();
    byte[] decoded = decoder.decode(result);
    //Now, just write each byte from the byte array to the output stream
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但是为了提高效率并且不将整个 Stream 存储在服务器上,创建了一个更复杂的任务。我们可以使用Base64.Decoder.wrap() 方法,但这样做的问题是,如果它达到无法解码的值,它会抛出 IOException(如果他们提供的方法只是将字节保留为是如果他们不能被解码?)。不幸的是,Base64 前缀无法解码,因为它不是 Base64 编码的。所以,它会抛出一个 IOException。

为了解决这个问题,我们必须使用 anInputStreamReader来读取InputStream指定适当的Charset. 然后我们必须int将从 InputStream 的 read() 方法调用接收到的 s 转换为chars。当我们达到适当数量的字符时,我们必须将其与 Base64 前缀的介绍(“数据”)进行比较。如果匹配,我们知道 Stream 包含前缀,所以继续阅读直到我们到达前缀结束字符(逗号:“,”)。最后,我们可以开始输出前缀之后的字节。例子:

S3Object obj = s3Client.getObject(new GetObjectRequest(bucketName, keyName));
Base64.Decoder decoder = Base64.getDecoder();
InputStream stream = obj.getObjectContent();
InputStreamReader reader = new InputStreamReader(stream);
try{
    return new StreamingOutput(){
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException{
            //for checking if string has base64 prefix
            char[] pre = new char[4]; //"data" has at most four bytes on a UTF-8 encoding
            boolean containsPre = false;
            int count = 0;
            int nextByte = 0;
            while((nextByte = stream.read()) != -1){
                if(count < pre.length){
                    pre[count] = (char) nextByte;
                    count++;
                }else if(count == pre.length){
                    //determine whether has prefix or not and act accordingly
                    count++;
                    containsPre = (Arrays.toString(pre).toLowerCase().equals("data")) ? true : false;
                    if(!containsPre){
                        //doesn't have Base64 prefix so write all the bytes until this point
                        for(int i = 0; i < pre.length; i++){
                            output.write((int) pre[i]);
                        }
                        output.write(nextByte);
                    }
                }else if(containsPre && count < 25){
                    //the comma character (,) is considered the end of the Base64 prefix
                    //so look for the comma, but be realistic, if we don't find it at about 25 characters
                    //we can assume the String is not encoded correctly
                    containsPre = (Character.toString((char) nextByte).equals(",")) ? false : true;
                    count++;
                }else{
                    output.write(nextByte);
                }
            }
            output.flush();
            output.close();
            stream.close();
        }
    };
}catch(Exception e){
    e.printStackTrace();
    return null;
}

在服务器上执行这似乎有点繁重的任务,所以我认为在客户端解码是一个更好的选择。不幸的是,大多数 Android 客户端库不支持 Base64 解码(尤其是带有前缀的)。但是,正如@tyronen 指出的那样,如果 String 已经获得, Fresco 确实支持它。不过,这消除了使用图像加载库的关键原因之一。

Android客户端解码

在客户端应用程序上解码非常容易。首先从 InputStream 中获取 String:

BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
    br = new BufferedReader(new InputStreamReader(stream));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    return sb.toString();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然后使用 Android 的 Base64 类解码字符串:

int i = result.indexOf(",");
result = result.substring(i + 1);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap bitMap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

Fresco 库似乎很难更新,因为它们使用了很多委托。因此,我继续使用 Picasso 图像加载库,并使用 Base64 解码能力创建了我自己的分支。

于 2015-08-25T20:35:34.820 回答