權限android
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
依賴git
maven { url 'https://jitpack.io' }
implementation 'com.github.LuckSiege.PictureSelector:picture_library:v2.6.0'
避免報錯github
而後由於PictureSelector須要項目minSdkVersion要大於或者等於19
而後最好添加
canvas
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
若是出現限制dex大小添加緩存
multiDexEnabled true
apply plugin: 'com.android.application' android { compileSdkVersion 30 buildToolsVersion "30.0.1" defaultConfig { applicationId "com.wd.circlesharingdemo" minSdkVersion 19 targetSdkVersion 30 versionCode 1 versionName "1.0" multiDexEnabled true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } }
使用bash
PictureSelector.create(activity) .openGallery(PictureMimeType.ofImage())//所有.PictureMimeType.ofAll()、圖片.ofImage()、視頻.ofVideo()、音頻.ofAudio() //.theme()//主題樣式(不設置爲默認樣式) 也可參考demo values/styles下 例如:R.style.picture.white.style .maxSelectNum(maxSize)// 最大圖片選擇數量 int .minSelectNum(1)// 最小選擇數量 int .imageEngine(GlideEngine.createGlideEngine()) .imageSpanCount(3)// 每行顯示個數 int .isCamera(true)// 是否顯示拍照按鈕 true or false .isZoomAnim(true)// 圖片列表點擊 縮放效果 默認true .isEnableCrop(true)// 是否裁剪 true or false .isCompress(true)// 是否壓縮 true or false .minimumCompressSize(100)// 小於100kb的圖片不壓縮 .forResult(PictureConfig.CHOOSE_REQUEST);//結果回調onActivityResult code
而後在onActivityResult裏面獲取圖片集合服務器
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { // 結果回調 List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data); //在這裏補充一下由於如今的數據格式是LocalMedia須要進行轉化不能強轉這樣會找不到路徑的 showSelectPic(selectList); } }
通過測試拍照上傳時會出現上傳不上去的狀況我還進行一次壓縮,拍照成功上傳網絡
/** * 關於圖片的工具類壓縮等 */ public class BitmapUtil { private static String PHOTO_FILE_NAME = "PMSManagerPhoto"; /** * 獲取圖片的旋轉角度 * * @param filePath * @return */ public static int getRotateAngle(String filePath) { int rotate_angle = 0; try { ExifInterface exifInterface = new ExifInterface(filePath); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotate_angle = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate_angle = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotate_angle = 270; break; } } catch (IOException e) { e.printStackTrace(); } return rotate_angle; } /** * 旋轉圖片角度 * * @param angle * @param bitmap * @return */ public static Bitmap setRotateAngle(int angle, Bitmap bitmap) { if (bitmap != null) { Matrix m = new Matrix(); m.postRotate(angle); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); return bitmap; } return bitmap; } //轉換爲圓形狀的bitmap public static Bitmap createCircleImage(Bitmap source) { int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight(); Paint paint = new Paint(); paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(target); canvas.drawCircle(length / 2, length / 2, length / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(source, 0, 0, paint); return target; } /** * 圖片壓縮-質量壓縮 * * @param filePath 源圖片路徑 * @return 壓縮後的路徑 */ public static String compressImage(String filePath) { //原文件 File oldFile = new File(filePath); //壓縮文件路徑 照片路徑/ String targetPath = oldFile.getPath(); int quality = 50;//壓縮比例0-100 Bitmap bm = getSmallBitmap(filePath);//獲取必定尺寸的圖片 int degree = getRotateAngle(filePath);//獲取相片拍攝角度 if (degree != 0) { //旋轉照片角度,防止頭像橫着顯示 bm = setRotateAngle(degree,bm); } File outputFile = new File(targetPath); try { if (!outputFile.exists()) { outputFile.getParentFile().mkdirs(); //outputFile.createNewFile(); } else { outputFile.delete(); } FileOutputStream out = new FileOutputStream(outputFile); bm.compress(Bitmap.CompressFormat.JPEG, quality, out); out.close(); } catch (Exception e) { e.printStackTrace(); return filePath; } return outputFile.getPath(); } /** * 根據路徑得到圖片信息並按比例壓縮,返回bitmap */ public static Bitmap getSmallBitmap(String filePath) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//只解析圖片邊沿,獲取寬高 BitmapFactory.decodeFile(filePath, options); // 計算縮放比 options.inSampleSize = calculateInSampleSize(options, 480, 800); // 完整解析圖片返回bitmap options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } /** * 質量壓縮Bitmap方法 * @param image * @return */ public static Bitmap compressImage1(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中 int options = 90; while (baos.toByteArray().length / 1024 > 100) { // 循環判斷若是壓縮後圖片是否大於100kb,大於繼續壓縮 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裏壓縮options%,把壓縮後的數據存放到baos中 options -= 10;// 每次都減小10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片 return bitmap; } /** * 如下是bitmap轉file(帶壓縮轉換 * @param context * @param bitmap * @param kb * @return */ /* * bitmap轉file(帶壓縮轉換 能夠本身設定 默認100kb) 上傳服務器的時候使用 */ public static String bitmapToFileWhithCompress(Context context , Bitmap bitmap , int kb) { String sdPath = getDiskCacheDir(context); String name = new DateFormat().format("yyyyMMddhhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg"; String picPath = sdPath + "/" + name; File outImage = new File(picPath); OutputStream outputStream = null; try { outputStream = new FileOutputStream(outImage); } catch (FileNotFoundException e) { e.printStackTrace(); } //調用了下面封裝好的壓縮方法返回已經壓縮的bitmap 而後再調用cmpress 輸出流把bitmap轉走 100再也不壓縮 由於已經壓縮好了 compressImage(bitmap,kb).compress(Bitmap.CompressFormat.JPEG, 100, outputStream); //返回一個壓縮圖片絕對路徑 return picPath; } /** * 獲取緩存文件夾的相對路徑 */ public static String getDiskCacheDir(Context ctx) { String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = ctx.getExternalCacheDir().getPath(); } else { cachePath = ctx.getCacheDir().getPath(); } return cachePath; } //無回調有返回值的壓縮方法 public static Bitmap compressImage(Bitmap image , int kb) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > kb) { //循環判斷若是壓縮後圖片是否大於設定的kb,大於繼續壓縮 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裏壓縮options%,把壓縮後的數據存放到baos中 options -= 10;//每次都減小10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮後的數據baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream數據生成圖片 return bitmap; } /** * file轉bitmap(進行壓縮,防止內存泄漏) */ public static Bitmap fileToBitmap(String imagePath,int kb) { Bitmap bitmap = null; try { File file = new File(imagePath); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; FileInputStream fis = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(fis, null, options); //將bitmap進行壓縮防止內存泄漏 bitmap = compressImage(bitmap,kb); fis.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } /* * bitmap轉file(原圖轉換) */ public static String bitmapToFile(Context context,Bitmap bitmap) { String sdPath = getDiskCacheDir(context); String name = new DateFormat().format("yyyyMMddhhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg"; String picPath = sdPath + "/" + name; File outImage = new File(picPath); OutputStream outputStream = null; try { outputStream = new FileOutputStream(outImage); } catch (FileNotFoundException e) { e.printStackTrace(); } bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); //返回一個圖片路徑 return picPath; } }
private void showSelectPic(List<LocalMedia> result) { fileList = new ArrayList<>(); for (int i = 0; i < result.size(); i++) { String path; //判斷是否10.0以上 if (Build.VERSION.SDK_INT >= 29) { path = result.get(i).getAndroidQToPath(); } else { path = result.get(i).getPath(); } newPath = BitmapUtil.compressImage(path);//壓縮 fileList.add(new File(newPath));//將路徑放到File集合裏面去傳到接口 Log.e(TAG, "圖片連接: " + path); //請求網絡上傳圖片 okRE.getInstance().postMoreImage(urls,headmap,map,fileList, new okRE.NetCallBack() { @Override public void onSuccess(String string) { Toast.makeText(MainActivity.this, string+"", Toast.LENGTH_SHORT).show(); } @Override public void onFail(String string) { Toast.makeText(MainActivity.this, string+"", Toast.LENGTH_SHORT).show(); } }); }
圖片預覽app
//圖片選擇器自帶預覽 PictureSelector.create(MainActivity.this) .themeStyle(R.style.picture_default_style) .isNotPreviewDownload(true)//是否顯示保存彈框 .imageEngine(GlideEngine.createGlideEngine()) // 選擇器展現不出圖片則添加 .openExternalPreview(position, 「選擇的圖片集合」);
使用方法maven
private List<LocalMedia> selectList = new ArrayList<>(); private List<String> Listss = new ArrayList<>();//好比這個是網絡請求圖片集合 private List<String> List = new ArrayList<>();//後臺返回多圖數據切割後集合 //注意若是多圖切割 String[] split = picture.split(","); List.add(split[i]) //看後臺返回數據狀況也可不進行切割 for (int i = 0; i < List.size(); i++) { LocalMedia localMedia = new LocalMedia(); localMedia.setPath(list.get(i)); selectList.add(localMedia); } PictureSelector.create(MainActivity.this) .themeStyle(R.style.picture_default_style) .isNotPreviewDownload(true)//是否顯示保存彈框 .imageEngine(GlideEngine.createGlideEngine()) .openExternalPreview(position, selectList);
以上就是PictureSelector的簡單使用若是須要項目demo
感謝觀看