我制作了一个小型的测试 Web 应用程序,使用 Nihilogic 的canvas2image JavaScript 库将 HTML 画布转换为图像,然后用生成的图像替换画布,并显示消息提示用户触摸(长按)该图像以将其保存到手机上。
我遇到的问题是,安卓默认的网页浏览器(“Internet”)不会呈现代表图像的 base64 编码数据流,而是显示一个问号标记。有解决方法吗?如果有,应该怎么做?
我制作了一个小型的测试 Web 应用程序,使用 Nihilogic 的canvas2image JavaScript 库将 HTML 画布转换为图像,然后用生成的图像替换画布,并显示消息提示用户触摸(长按)该图像以将其保存到手机上。
我遇到的问题是,安卓默认的网页浏览器(“Internet”)不会呈现代表图像的 base64 编码数据流,而是显示一个问号标记。有解决方法吗?如果有,应该怎么做?
使用自定义的ContentProvider并重写openFile()方法以返回流作为临时文件。
你可以在HTML A标签中使用URI作为资源地址。
<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();
}
}
}
}
基于@goldenparrot的评论,可以看到图像。
<img src="data:image/png;base64,BASE64_STRING_HERE" />
当页面加载时,如果已经存在base64数据,则可以使用建议的css背景图像。然而,当完全相同的数据字符串动态输入时,由于某种原因它不起作用。即使是静态加载的带有base64数据的图像也存在问题:它无法对长按做出任何反应,因此无法下载。我正在使用Android 2.3.6。
编辑:您还可以尝试添加其他下载链接。
<a href="data:application/octet-stream;base64,BASE64_STRING_HERE">download file</a>
但对我没有用。Android只是将该文件的内容显示为文本。普通桌面Web浏览器打开了“下载文件”对话框,但没有为该文件建议任何扩展名,因此用户必须手动添加。
另请参见{{link1:浏览器/HTML强制从src =“data:image / jpeg; base64 ...”下载图像}}
我的测试HTML页面是{{link2:http://kuitsi.bitbucket.org/stackoverflow12113616.html}}
background-image: url(data:image/png;base64datahere....);
创建一个div,而不是创建一个带有src属性的img标签吗? - Prasanth