在Android浏览器中将图像渲染为数据流

Render Image as Data stream in Android browser

本文关键字:数据流 图像 Android 浏览器      更新时间:2023-09-26

我制作了一个小型的测试web应用程序,它将HTML画布转换为图像(通过使用Nihilogic的canvas2imageJavaScript库),然后用生成的图像替换画布,并显示一条消息,通知用户触摸(长)该图像以便将其保存到手机中。

我遇到的问题是,Android的默认网络浏览器("Internet")不会呈现代表图像的base64编码数据流,而是显示一个问号。有办法解决这个问题吗?如果是,那么怎么做?

使用自定义ContentProvider并覆盖openFile()以Tempfile形式返回流。

您可以将URI用作html A标记中的src。

<a src="Example://file"></a>
public class ExampleProvider extends ContentProvider {
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {         
        //Get your bitmap
        Bitmap bmp = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.file_example);
        File tempFile = null;
        try {
            //Create the tempfile form a stream
            tempFile = File.createTempFile("tempfile", ".thumb", getContext().getCacheDir());
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
            if(mode.equals("r")) {
              return ParcelFileDescriptor.open(tempFile, ParcelFileDescriptor.MODE_READ_ONLY);
            }
        }
        catch(IOException e)  {
            LOGGER.error("Couldn't generate temp file for thumb view, guid:" + guid, e);
        }
        finally {
            if(tempFile != null {
                //The unix filesystem automatically deletes the file once all handles are gone
                tempFile.delete();
            }
        }
    }
}

根据@goldenparot的评论,可以用看到图像

<img src="data:image/png;base64,BASE64_STRING_HERE" />

当页面加载时base64数据已经存在时,(以及建议的css背景图像)。然而,由于某些原因,当完全相同的数据字符串被动态输入时,它不起作用。即使是带有base64数据的静态加载图像也存在问题:它对长时间点击没有任何反应,因此无法下载。我使用的是安卓2.3.6。

编辑:您也可以尝试添加额外的下载链接

<a href="data:application/octet-stream;base64,BASE64_STRING_HERE">download file</a>

但它对我不起作用。Android只是将该文件的内容显示为文本。普通的桌面web浏览器确实打开了"下载文件"对话框,但并没有建议该文件的任何扩展名,所以用户必须手动添加。

另请参见Browser/HTML强制从src下载图像=";数据:图像/jpeg;base64…";

我的测试html页面是http://kuitsi.bitbucket.org/stackoverflow12113616.html