从InputStream

时间:2015-08-21 16:27:07

标签: java stream base64 inputstream fresco

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

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

问题: 为了简化我的代码而不是重新发明轮子,我正在使用Android客户端的图像库来处理图像的加载,显示和缓存(确切地说是Facebook的Fresco Library)。但是,没有库似乎支持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的情况下从发送到客户端的Stream中删除Base64前缀?这可能吗?

1 个答案:

答案 0 :(得分:0)

  

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

将流发送到客户端时删除前缀证明是一项非常复杂的任务。如果您不介意将整个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);
    }
    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() method,但问题是如果它达到一个无法解码的值,它会抛出一个IOException(如果它们提供的方法只是保留了字节,那就不好了)如果他们无法解码?)。不幸的是,Base64前缀无法解码,因为它不是Base64编码的。因此,它会抛出IOException。

要解决此问题,我们必须使用InputStreamReader来使用指定的相应InputStream阅读Charset。然后我们必须将从InputStream的read()方法调用中收到的int转换为char s。当我们达到适当数量的字符时,我们必须将它与Base64前缀的介绍(&#34;数据&#34;)进行比较。如果它匹配,我们知道Stream包含前缀,所以继续阅读直到我们到达前缀结束字符(逗号:&#34;,&#34;)。最后,我们可以开始流出前缀后的字节。例如:

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指出Fresco does support it,如果已经获得了String。但是,这消除了使用图像加载库的一个关键原因。

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类解码String:

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解码能力的own fork of it

相关问题