android加載系統相冊圖片並顯示詳解

1,下載ImageLoad.jar包放入項目libs文件夾中,並點擊右鍵—>add as Library

2,首先記得在Manifest.xml註冊權限(註:6.0以後的版本要在代碼中動態註冊權限)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

3,佈局文件,一個ImageView用來顯示加載的圖片,Button點擊後進入系統相冊選取圖片

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.zcn.demo.loadgallerypicture.MainActivity">

    <ImageView
        android:id="@+id/pic"
        android:src="@mipmap/ic_launcher"
        android:layout_width="120dp"
        android:layout_height="120dp" />
    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="bottom"
        android:text="button"/>
</LinearLayout>

4,.java文件

package com.zcn.demo.loadgallerypicture;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static int WRITE_SD_CODE = 1;
    private static int READ_SD_CODE = 2;
    private static String TAG = "ZCN_MainActivity";
    private ImageView image;
    private Button btn;

    private String pic_path;
    private DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView)findViewById(R.id.pic);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
    }

    //android 6.0 以上版本要手動要求權限
    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},READ_SD_CODE);
        }else {
            Log.v(TAG, "6.0一下版本直接打開相冊....");
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);
        }
    }

    //權限選擇結果接收
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_SD_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用戶授予瞭此權限
                // 調用android自帶的圖庫
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);
            } else {
                // 用戶拒絕瞭此權限
            }
        }
    }

    public interface ActivityRequestCode {
        public static final int SHOW_MAP_DEPOT = 1; //顯示Android自帶圖庫,用於選擇用戶自己的圖片
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == ActivityRequestCode.SHOW_MAP_DEPOT
                    && resultCode == Activity.RESULT_OK)
                showPic(resultCode,data);
        }
    }

    // 調用android自帶圖庫,顯示選中的圖片
    private void showPic(int resultCode,Intent data) {
        if(resultCode== Activity.RESULT_OK) {
            if (data!=null) {
                Uri uri = data.getData();
                Log.v(TAG, "uri = "+uri);
                if (uri!=null) {
                    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                    //選擇的就隻是一張圖片,所以cursor隻有一條記錄
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            String path = cursor.getString(cursor.getColumnIndex("_data"));//獲取相冊路徑字段
                            Log.v(TAG, "打開相冊獲取的圖片sd卡路徑:" + path);
                            File file = new File(path);
                            initOptions();
                            ImageLoader.getInstance().displayImage(uri.toString(), image,options);
                            //保存圖片到data/data/files文件夾下
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                            File f = getFileStreamPath("ic_mine_head_portrait.jpg");
                            Log.d(TAG, "File path :" + file.getParentFile());
                            if (!f.exists()) {
                                Log.d(TAG, "文件不存在");
                                FileOutputStream out = null;
                                try{
                                    f.createNewFile();
                                    out = new FileOutputStream(f);
                                    if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out))
                                    {
                                        out.flush();
                                        out.close();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }finally {
                                    try {
                                        out.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else{
            Log.d(TAG,"放棄從相冊選擇");
        }
    }

    private void initOptions(){
        options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.ic_main_ad_stub) // 設置圖片下載期間顯示的圖片
                .showImageForEmptyUri(R.mipmap.ic_main_ad_empty) // 設置圖片Uri為空或是錯誤的時候顯示的圖片
                .showImageOnFail(R.mipmap.ic_main_ad_error) // 設置圖片加載或解碼過程中發生錯誤顯示的圖片
                .cacheInMemory(true) // 設置下載的圖片是否緩存在內存中
                .cacheOnDisc(true) // 設置下載的圖片是否緩存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 設置成圓角圖片
                .build(); // 創建配置過得DisplayImageOption對象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
}

後續:顯示圖片所使用的uri:

String imageUri = "http://site.com/image.png"; // from Web
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
String imageUri = "content://media/external/audio/albumart/13"; // from content provider
String imageUri = "assets://image.png"; // from assets
String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)

註意:使用drawable://除非你真的需要他。時刻要註意使用本地圖片加載方法:setImageResource帶代替ImageLoader。

到此這篇關於android加載系統相冊圖片並顯示詳解的文章就介紹到這瞭,更多相關android加載相冊圖片內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: