Android webview加载本地图片

本文介绍了三种让WebView加载和操作本地文件的方法:使用WebView资源拦截与回调、Base64编码和ContentProvider。其中详细讲解了如何通过ContentProvider来兼容旧版系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出于安全的考虑,一般情况下webview并不允许网页读取和操作网页文件所在文件夹外的文件。

在网上搜索后,发现有3种可行的方法:

1、使用WebView自身的资源拦截与回调来实现该功能;
WebView的shouldInterceptRequest回调从API 11才开始引入,所以使用该方法不能兼容2.2与2.3的系统;

2、img的src使用base64的编码格式,这种方法会造成html文件较大,轻量的网页可以考虑使用;

3、img的src使用content协议,通过ContentProvider来进行提供相应资源; 

方法2和方法3都可以兼容2.x的系统


方法3的例子:

com.packagename.provider;
public class MyProvider extends ContentProvider { 
     @Override
     public ParcelFileDescriptor openFile(Uri uri, String mode){
        URI fileURI = URI.create( "file://" + uri.getPath() );
        File file = new File( fileURI );

        ParcelFileDescriptor parcel = null;
        try {
            parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            Log.e( TAG, "Error finding: " + fileURI + "\n" + e.toString() );
        }

        return parcel;

AndroidManifest.xml

 <provider
        android:name=".provider.MyProvider"
        android:authorities="com.packagename" />

You can then access your files which would normally be

 file://sdcard/Android/data/com.packagename/image.jpg

by using

 content://com.packagename/sdcard/Android/data/com.packagename/image.jpg

So essentially replace file:// with content://com.packagename


http://stackoverflow.com/questions/11303118/android-set-a-local-image-to-an-img-element-in-webview



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值