android 获取本地图片资源

三种方式:

1.通过摄像头拍摄获取。

2.通过读取本地image类型文件,可以是png,jpg等,所以是image/*。

3.第三种方式比较麻烦,是通过读取系统存储Provider获取到图片路径后,整理显示到应用内。

通过代码分别介绍实现方式:

1.通过摄像头获取

权限问题:

使用api23以上编译,在6.0系统运行

需要动态获取权限,相关接口在Debug类中。

其他情况在清单文件中配置即可:

<span style="white-space:pre">	</span><uses-permission android:name="android.permission.CAMERA"/>//摄像头权限,SD卡读写权限
<span style="white-space:pre">	</span><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<span style="white-space:pre">	</span><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

相关代码:

<span style="white-space:pre">	</span>//主要是指定好文件的输出目录,通过onActivityResult接口监听回调,从制定的路径查找即可。
<span style="white-space:pre">	</span>Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String imgurl = new File(FileUtils.getTriImgDir(), System.currentTimeMillis() + "").getAbsolutePath();
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imgurl)));
        startActivityForResult(openCameraIntent, requestcode);<span style="font-family: Arial, Helvetica, sans-serif;">	</span>

2.通过读取文件获取

权限问题同以上相同。

相关代码:

<span style="white-space:pre">	</span>//两种方式,一种是4.4以上的通过open_document获取,另一种是4.4以下通过get_content方式获取,区别在于onActivityResult返回值,非常麻烦。
<span style="white-space:pre">	</span>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, requestcode);
        } else {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, requestcode);
        }
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_7_285269" name="code" class="java"><span style="white-space:pre">	</span>//onActivityResult对两种方式返回的处理
<span style="white-space:pre">	</span>Uri uri = data.getData();//通过intent获取到uri这个一样,以下就要区别对待了,非常麻烦,但是基本都是通过uri再去系统媒体库中获取了。
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_10_7044548" name="code" class="java"><span style="white-space:pre">	public static String getPath(Context context, Uri uri) {
     	boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
	     if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                String documentId = DocumentsContract.getDocumentId(uri);
                String[] split = documentId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownLoadsDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                String[] split = id.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }


                String selection = "_id=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if (isKitKat && !DocumentsContract.isDocumentUri(context, uri)) {
            return selectImage(context, uri);
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }</span>
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_12_8973231" name="code" class="java">    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    public static boolean isDownLoadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
</pre><pre code_snippet_id="1885512" snippet_file_name="blog_20160918_14_8950067" name="code" class="java"><span style="white-space:pre">	</span>public static String selectImage(Context context, Uri uri) {
        String picturePath = "";
        if (uri != null) {
            String uriStr = uri.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                picturePath = null;
            }
        } else {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        return picturePath;
    }
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};


        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

3.最后一种其实比较简单,只不过是我们要写的代码多一点,以附件形式上传文件 http://download.csdn.net/detail/lilinwang1990/9633178




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Android中,我们可以使用Html.fromHtml()方法来解析带有HTML标签的字符串,并转换为Android的格式。 要获取本地资源,可以使用以下步骤: 1. 在Android项目的assets文件夹下创建一个名为"html"的文件夹,将要加载的HTML文件放入其中。例如,我们将假设有一个名为"local.html"的HTML文件。 2. 创建一个WebView来加载并显示HTML内容。在XML布局文件中,添加一个WebView控件: ```xml <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> ``` 3. 在Java代码中,找到并设置WebView控件: ```java WebView webView = findViewById(R.id.webview); // 加载本地HTML文件 webView.loadUrl("file:///android_asset/html/local.html"); // 也可以使用字符串显示HTML内容 // webView.loadDataWithBaseURL(null, "<html><body>你好,世界!</body></html>", "text/html", "utf-8", null); ``` 上述代码中,我们使用了webView.loadUrl()方法来加载本地HTML文件。注意,方法中的URL是以"file:///android_asset/"为前缀的,这是指向项目的assets文件夹的路径。 4. 确保在AndroidManifest.xml文件中添加了Internet权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 以上就是在Android中解析并获取本地资源的基本步骤。你可以根据自己的需求对WebView进行更多的定制和处理。 ### 回答2: 在Android上解析HTML并获取本地资源可以通过以下几个步骤实现: 1. 首先,需要使用合适的HTML解析库,例如Jsoup。可以通过将该库添加到项目的Gradle文件中进行引入。 2. 在Android应用的assets或res目录下,将HTML文件作为本地资源嵌入到项目中。 3. 在代码中,使用Jsoup库加载并解析HTML文件。可以通过以下代码示例实现: ```java // 加载本地HTML文件 String htmlString = ""; try { InputStream inputStream = getAssets().open("local_html.html"); // 替换local_html.html为实际的HTML文件名 int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); htmlString = new String(buffer, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // 解析HTML并获取本地资源 Document doc = Jsoup.parse(htmlString); Elements imgElements = doc.select("img"); // 获取所有的<img>标签 for (Element img : imgElements) { String imgUrl = img.attr("src"); // 获取<img>标签的src属性值 // 可以在此处处理获取到的本地资源路径 // 例如可以通过加载本地图片资源的方式显示图片,或者获取到其他类型的本地资源文件路径等等 } ``` 通过以上步骤,就可以成功解析HTML文件并获取其中的本地资源。根据实际需求,可以进一步处理获取到的本地资源路径,并进行相应的操作。 ### 回答3: 在Android中,我们可以使用Html解析器来解析HTML代码,并获取其中的本地资源。下面是一种常用的方法: 首先,我们需要使用Html解析器类来解析HTML代码Android提供了一个Html类,可以用于解析和处理HTML代码。我们可以使用它的fromHtml()方法将HTML代码转换为Spannable对象。 接下来,我们可以使用Spannable对象的getSpans()方法来获取Spannable对象中的本地资源。Spannable对象使用Span类来标记文本的不同样式和属性,其中包含了我们想要获取的本地资源。通过迭代Spannable对象中的Span数组,我们可以判断每个Span对象是否是我们需要的类型,并从中获取本地资源。 具体的步骤如下所示: 1. 在我们的Android项目中,导入Html类: import android.text.Html; 2. 解析HTML代码并返回Spannable对象: String htmlCode = "<img src='file:///android_res/drawable/image.png'>"; // 假设这是我们的HTML代码 Spannable spannable = (Spannable) Html.fromHtml(htmlCode); 3. 获取Spannable对象中的本地资源: ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class); for (ImageSpan span : imageSpans) { String imagePath = span.getSource(); // 获取本地资源路径 // 执行相应的操作,比如加载图片等 } 在上述步骤中,我们首先将HTML代码转换为Spannable对象,然后使用getSpans()方法获取Spannable对象中的ImageSpan对象,通过ImageSpan对象的getSource()方法获取本地资源的路径。最后,我们可以根据路径执行相应的操作,比如加载图片等。 请注意,上述方法仅适用于获取HTML代码中的图片资源。如果想要获取其他类型的本地资源,可以相应地修改代码。 以上是在Android中解析HTML代码获取本地资源的简要介绍。希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值