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

时间:2012-08-24 16:53:36

标签: javascript android html5-canvas

我整理了一个小的test web app,它将HTML画布转换为图像(使用Nihilogic的 canvas2image JavaScript库),然后用生成的图像替换画布并显示消息通知用户触摸(长)该图像以便将其保存到手机中。

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

2 个答案:

答案 0 :(得分:4)

使用自定义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();
            }
        }
    }
}

答案 1 :(得分:1)

根据@goldenparrot图片的评论可以看到

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

(以及建议的css background-image)当加载页面时已存在base64数据。但是,当动态输入完全相同的数据字符串时,它不能用于某些原因。即使是带有base64数据的静态加载图像也存在问题:它不会以任何方式对长按做出反应,因此无法下载。我正在使用Android 2.3.6。

修改:您还可以尝试添加其他下载链接

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

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

另见Browser/HTML Force download of image from src="data:image/jpeg;base64..."

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