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加载相册图片内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)