權限
<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" />
依賴
maven { url 'https://jitpack.io' }
implementation 'com.github.LuckSiege.PictureSelector:picture_library:v2.6.0'
避免報錯
然后因為PictureSelector需要專案minSdkVersion要大于或者等于19
然后最好添加
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
}
}
使用
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();
}
});
}
圖片預覽
//圖片選擇器自帶預覽
PictureSelector.create(MainActivity.this)
.themeStyle(R.style.picture_default_style)
.isNotPreviewDownload(true)//是否顯示保存彈框
.imageEngine(GlideEngine.createGlideEngine()) // 選擇器展示不出圖片則添加
.openExternalPreview(position, “選擇的圖片集合”);
使用方法
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
PictureSelector的使用demo
感謝觀看
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/227558.html
標籤:其他
上一篇:Android程式員面試最新實況!含淚親訴一波三折的阿里巴巴之旅...
下一篇:沒有卡頓的全域設定防暴力點擊事件
