android怎么调用系统自带的图库打开指定目录的相册

android怎么调用系统自带的图库打开指定目录的相册,第1张

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

//完成照相后回调用此方法

superonActivityResult(requestCode, resultCode, data);

case 1:

switch (resultCode) {

case ActivityRESULT_OK://照相完成点击确定

String sdStatus = EnvironmentgetExternalStorageState();

if (!sdStatusequals(EnvironmentMEDIA_MOUNTED)) { // 检测sd是否可用

Logv("TestFile", "SD card is not avaiable/writeable right now");

return; }

Bundle bundle = datagetExtras();

Bitmap bitmap = (Bitmap) bundleget("data");// 获取相机返回的数据,并转换为Bitmap格式

FileOutputStream b = null;

File file = new File("/sdcard/pk4fun/");

filemkdirs();// 创建文件夹,名称为pk4fun // 照片的命名,目标文件夹下,以当前时间数字串为名称,即可确保每张照片名称不相同。网上流传的其他Demo这里的照片名称都写死了,则会发生无论拍照多少张,后一张总会把前一张照片覆盖。细心的同学还可以设置这个字符串,比如加上“IMG”字样等;然后就会发现sd卡中myimage这个文件夹下,会保存刚刚调用相机拍出来的照片,照片名称不会重复。

String str = null;

Date date = null;

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 获取当前时间,进一步转化为字符串

date = new Date(resultCode);

str = formatformat(date);

String fileName = "/sdcard/myImage/" + str + "jpg";

sendBroadcast(fileName);

try {

b = new FileOutputStream(fileName);

bitmapcompress(BitmapCompressFormatJPEG, 100, b);// 把数据写入文件

} catch (FileNotFoundException e) {

eprintStackTrace();

} finally {

try {

bflush();

bclose();

} catch (IOException e) {

eprintStackTrace();

}

} break;

case ActivityRESULT_CANCELED:// 取消

break;

}

break;

case 2:

switch (resultCode) {

case ActivityRESULT_OK: {

Uri uri = datagetData();

Cursor cursor = mActivitygetContentResolver()query(uri, null,

null, null, null);

cursormoveToFirst();

String imgNo = cursorgetString(0); // 编号

String imgPath = cursorgetString(1); // 文件路径

String imgSize = cursorgetString(2); // 大小

String imgName = cursorgetString(3); // 文件名

cursorclose();

// Options options = new BitmapFactoryOptions();

// optionsinJustDecodeBounds = false;

// optionsinSampleSize = 10;

// Bitmap bitmap = BitmapFactorydecodeFile(imgPath, options);

}

break;

case ActivityRESULT_CANCELED:// 取消

break;

}

break;

}

1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,在本地sd卡存一份(如果有的话,没有则内部存储,所以还

需要判断用户是否挂载了sd卡),然后在服务器上存储一份该,当下次再次启动应用时,会默认去sd卡加载该,如果本地没有,再会去联网请求

2、使用了picasso框架以及自定义BitmapUtils工具类

3、记得加上相关权限

<uses-permission android:name="androidpermissionINTERNET"></uses-permission>

<uses-permission android:name="androidpermissionCAMERA"/>

<uses-permission android:name="androidpermissionWRITE_EXTERNAL_STORAGE"></uses-permission>

/

public class MainActivity extends AppCompatActivity implements ViewOnClickListener {

private ImageView iv;//要设置的头像

private Button btn_photo;//调用相册按钮

private Button btn_camera;//调用相机按钮

@Override

protected void onCreate(Bundle savedInstanceState) {

superonCreate(savedInstanceState);

setContentView(Rlayoutactivity_main);

iv=(ImageView) findViewById(Ridiv);

btn_photo = (Button) findViewById(Ridbtn_photo);

btn_camera = (Button) findViewById(Ridbtn_camera);

btn_photosetOnClickListener(this);

btn_camerasetOnClickListener(this);

}

@Override

public void onClick(View v) {

switch (vgetId()) {

case Ridbtn_photo://打开系统相册

Intent intent=new Intent(IntentACTION_PICK, MediaStoreImagesMediaEXTERNAL_CONTENT_URI);

startActivityForResult(intent,100);

break;

case Ridbtn_camera://打开系统相机

Intent intent2=new Intent(MediaStoreACTION_IMAGE_CAPTURE);

startActivityForResult(intent2,200);

break;

}

}

@RequiresApi(api = BuildVERSION_CODESKITKAT)

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

superonActivityResult(requestCode, resultCode, data);

if(requestCode==100&&resultCode==RESULT_OK&&data!=null){//系统相册

Uri imageData = datagetData();

String path=getPath(imageData);

Bitmap bitmap = BitmapFactorydecodeFile(path);

Bitmap bitmap1 = BitmapUtilszoom(bitmap, ivgetWidth(), ivgetHeight());

Bitmap bitmap2 = BitmapUtilscircleBitmap(bitmap1);

//加载显示

ivsetImageBitmap(bitmap2);

//bitmap上传到服务器

//bitmap保存到本地

saveImage(bitmap2);

}else if(requestCode==200&&resultCode==RESULT_OK&&data!=null){//系统相机

Bitmap bitmap = (Bitmap) datagetExtras()get("data");

BitmapUtilszoom(bitmap,ivgetWidth(),ivgetHeight());

bitmap=BitmapUtilscircleBitmap(bitmap);

//加载显示

ivsetImageBitmap(bitmap);

//bitmap上传到服务器

//bitmap保存到本地

saveImage(bitmap);

}

}

/

数据的存储。(5种)

Bimap:内存层面的对象。

存储--->内存:

BitmapFactorydecodeFile(String filePath);

BitmapFactorydecodeStream(InputStream is);

内存--->存储:

bitmapcompress(BitmapCompressFormatPNG,100,OutputStream os);

/

private void saveImage(Bitmap bitmap) {

File filesDir;

if(EnvironmentgetExternalStorageState()equals(EnvironmentMEDIA_MOUNTED)){//判断sd卡是否挂载

//路径1:storage/sdcard/Android/data/包名/files

filesDir = thisgetExternalFilesDir("");

}else{//手机内部存储

//路径:data/data/包名/files

filesDir = thisgetFilesDir();

}

FileOutputStream fos = null;

try {

File file = new File(filesDir,"iconpng");

fos = new FileOutputStream(file);

bitmapcompress(BitmapCompressFormatPNG, 100,fos);

} catch (FileNotFoundException e) {

eprintStackTrace();

}finally{

if(fos != null){

try {

fosclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

//如果本地有,就不需要再去联网去请求

private boolean readImage() {

File filesDir;

if(EnvironmentgetExternalStorageState()equals(EnvironmentMEDIA_MOUNTED)){//判断sd卡是否挂载

//路径1:storage/sdcard/Android/data/包名/files

filesDir = getExternalFilesDir("");

}else{//手机内部存储

//路径:data/data/包名/files

filesDir = getFilesDir();

}

File file = new File(filesDir,"iconpng");

if(fileexists()){

//存储--->内存

Bitmap bitmap = BitmapFactorydecodeFile(filegetAbsolutePath());

ivsetImageBitmap(bitmap);

return true;

}

return false;

}

@RequiresApi(api = BuildVERSION_CODESKITKAT)

private String getPath(Uri uri) {

int sdkVersion = BuildVERSIONSDK_INT;

//高于442的版本

if (sdkVersion >= 19) {

Loge("TAG", "uri auth: " + urigetAuthority());

if (isExternalStorageDocument(uri)) {

String docId = DocumentsContractgetDocumentId(uri);

String[] split = docIdsplit(":");

String type = split[0];

if ("primary"equalsIgnoreCase(type)) {

return EnvironmentgetExternalStorageDirectory() + "/" + split[1];

}

} else if (isDownloadsDocument(uri)) {

final String id = DocumentsContractgetDocumentId(uri);

final Uri contentUri = ContentUriswithAppendedId(Uriparse("content://downloads/public_downloads"),

LongvalueOf(id));

return getDataColumn(this, contentUri, null, null);

} else if (isMediaDocument(uri)) {

final String docId = DocumentsContractgetDocumentId(uri);

final String[] split = docIdsplit(":");

final String type = split[0];

Uri contentUri = null;

if ("image"equals(type)) {

contentUri = MediaStoreImagesMediaEXTERNAL_CONTENT_URI;

} else if ("video"equals(type)) {

contentUri = MediaStoreVideoMediaEXTERNAL_CONTENT_URI;

} else if ("audio"equals(type)) {

contentUri = MediaStoreAudioMediaEXTERNAL_CONTENT_URI;

}

final String selection = "_id=";

final String[] selectionArgs = new String[]{split[1]};

return getDataColumn(this, contentUri, selection, selectionArgs);

} else if (isMedia(uri)) {

String[] proj = {MediaStoreImagesMediaDATA};

Cursor actualimagecursor = thismanagedQuery(uri, proj, null, null, null);

int actual_image_column_index = actualimagecursorgetColumnIndexOrThrow(MediaStoreImagesMediaDATA);

actualimagecursormoveToFirst();

return actualimagecursorgetString(actual_image_column_index);

}

} else if ("content"equalsIgnoreCase(urigetScheme())) {

// Return the remote address

if (isGooglePhotosUri(uri))

return urigetLastPathSegment();

return getDataColumn(this, uri, null, null);

}

// File

else if ("file"equalsIgnoreCase(urigetScheme())) {

return urigetPath();

}

return null;

}

/

uri路径查询字段

@param context

@param uri

@param selection

@param selectionArgs

@return

/

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 = contextgetContentResolver()query(uri, projection, selection, selectionArgs, null);

if (cursor != null && cursormoveToFirst()) {

final int index = cursorgetColumnIndexOrThrow(column);

return cursorgetString(index);

}

} finally {

if (cursor != null)

cursorclose();

}

return null;

}

private boolean isExternalStorageDocument(Uri uri) {

return "comandroidexternalstoragedocuments"equals(urigetAuthority());

}

public static boolean isDownloadsDocument(Uri uri) {

return "comandroidprovidersdownloadsdocuments"equals(urigetAuthority());

}

public static boolean isMediaDocument(Uri uri) {

return "comandroidprovidersmediadocuments"equals(urigetAuthority());

}

public static boolean isMedia(Uri uri) {

return "media"equals(urigetAuthority());

}

/

@param uri The Uri to check

@return Whether the Uri authority is Google Photos

/

public static boolean isGooglePhotosUri(Uri uri) {

return "comgoogleandroidappsphotoscontent"equals(urigetAuthority());

}

/

判断本地是否有该,没有则去联网请求

/

@Override

protected void onResume() {

superonResume();

if(readImage()){

return;

}

}

}

//BitmapUtils工具类public class BitmapUtils { /

该方法用于将进行圆形处理

/ public static Bitmap circleBitmap(Bitmap source){ //默认只对宽进行处理 int width=sourcegetWidth(); Bitmap bitmap=BitmapcreateBitmap(width,width,BitmapConfigARGB_8888); Canvas canvas=new Canvas(bitmap); Paint paint=new Paint(); //设置抗锯齿 paintsetAntiAlias(true); canvasdrawCircle(width/2,width/2,width/2,paint); paintsetXfermode(new PorterDuffXfermode(PorterDuffModeSRC_IN)); canvasdrawBitmap(source,0,0,paint); return bitmap; } / 该方法用于压缩处理,注意width、height参数的类型必须是float / public static Bitmap zoom(Bitmap source,float width,float height){ Matrix matrix=new Matrix(); //进行压缩处理 matrixpostScale(width/sourcegetWidth(),height/sourcegetHeight()); Bitmap bitmap = BitmapcreateBitmap(source, 0, 0, sourcegetWidth(), sourcegetHeight(), matrix, false); return bitmap; }}

以上所述是小编给大家介绍的Android实现调用系统图库与相机设置头像并保存在本地及服务器 ,希望对大家有所帮助

先引入Environment类,然后调用getExternalStorageDirectory()函数获得sd卡路径,然后连接在你的filename前面,应该就可以解决

具体:

import androidosEnvironment;

File f = new File(EnvironmentgetExternalStorageDirectory() + fileName);

其他用到fileName的地方类似

另外,读写sd卡需要在AndroidManifestxml文件内加入权限,具体:

<uses-permission android:name="androidpermissionWRITE_EXTERNAL_STORAGE" />

以上就是关于android怎么调用系统自带的图库打开指定目录的相册全部的内容,包括:android怎么调用系统自带的图库打开指定目录的相册、安卓从手机相册获取照片作为头像缓存地址、android 调用相册的图片 图片无法找到 路径应该怎么写等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9418050.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存