在entity.getContent()中解码从internet接收的base64图像



我正在从PHP向Android发送一个base64格式的图像。在安卓方面,以前当我是entity.toString()时,它运行得很好。我能够解码结果并创建位图。但现在我想知道这个图片下载了多少。所以我使用response.getHeaders("Content-Length")和entity.getContent();我正在从InputStream将其读取到byte[]数组中。无论我读了多少书,我都会把它转换成字符串。并附加到最终图像_base64问题是我在最后一个字符串中没有得到相同的原始base64值。还有别的办法吗?

       buf = new byte[totalSize];
        do {
            numBytesRead = stream.read(buf, numBytesRead, totalSize);
            String temp = Base64.encodeToString(buf,Base64.DEFAULT);
            image_base64 = image_base64 + temp;
            buf = new byte[totalSize];
            if (numBytesRead > 0) {
                downloadedSize += numBytesRead;
                dialog.setProgress((downloadedSize/totalSize)*100);
            }
        } while (numBytesRead > 0);
  1. 为什么还要使用base64呢?为什么不直接在PHP中输出图像并使用您在Android上获得的字节数组呢?为什么要浪费带宽和处理能力?

  2. base64字符串不匹配的原因可能是,当您收到它时,您编码而不是解码

  3. 你不能只对base64字符串的一部分进行编码/解码,你需要完整的。

  4. stream.read中使用downloadedSize而不是numBytesRead,否则将覆盖以前接收到的数据。

所以,如果你真的想使用base64:

buf = new byte[totalSize];
while(downloadedSize < totalSize)
{
    numBytesRead = stream.read(buf, downloadedSize, totalSize);
    if(numBytesRead > 0)
    {
        downloadedSize += numBytesRead;
        dialog.setProgress((downloadedSize/totalSize)*100);
    }
}
image_base64 = new String(buf);
// Now base64-decode it

最新更新