android选择相册
❶ Android studio从相册里面选图片无法选中
该功能主要实现上传图片到服务器,选择图片的方式有两种,一种是从手机相册中选择,另一种是调用手机摄像头拍照。
1.从相册选择的图片会存储到 data 里面,而相机拍照的图片不会存储到 data 里面。
2.由于从相册选择的图片会存储到 data 里面,而相机拍照的图片不会存储到 data 里面,所以在获取图片资源进行回显的方式不同,请看一下详细代码:(一定要创建文件 createFileName())。
❷ android调用手机拍照以及从相册选择照片需要判断版本号吗
举个实际例子看看吧。
/*用来标识请求照相功能的activity*/
private static final int CAMERA_WITH_DATA = 3023;
/*用来标识请求gallery的activity*/
private static final int PHOTO_PICKED_WITH_DATA = 3021;
/*拍照的照片存储位置*/
private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
private File mCurrentPhotoFile;//照相机拍照得到的图片
[java] view
plain
private void doPickPhotoAction() {
Context context = EditContact.this;
// Wrap our context to inflate list items using correct theme
final Context dialogContext = new ContextThemeWrapper(context,
android.R.style.Theme_Light);
String cancel="返回";
String[] choices;
choices = new String[2];
choices[0] = getString(R.string.take_photo); //拍照
choices[1] = getString(R.string.pick_photo); //从相册中选择
final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
android.R.layout.simple_list_item_1, choices);
final AlertDialog.Builder builder = new AlertDialog.Builder(
dialogContext);
builder.setTitle(R.string.attachToContact);
builder.setSingleChoiceItems(adapter, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch (which) {
case 0:{
String status=Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
doTakePhoto();// 用户点击了从照相机获取
}
else{
showToast("没有SD卡");
}
break;
}
case 1:
doPickPhotoFromGallery();// 从相册中去获取
break;
}
}
});
builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
/**
* 拍照获取图片
*
*/
protected void doTakePhoto() {
try {
// Launch camera to take photo for selected contact
PHOTO_DIR.mkdirs();// 创建照片的存储目录
mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
final Intent intent = getTakePickIntent(mCurrentPhotoFile);
startActivityForResult(intent, CAMERA_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.photoPickerNotFoundText,
Toast.LENGTH_LONG).show();
}
}
public static Intent getTakePickIntent(File f) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
return intent;
}
/**
* 用当前时间给取得的图片命名
*
*/
private String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(
"'IMG'_yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date) + ".jpg";
}
// 请求Gallery程序
protected void doPickPhotoFromGallery() {
try {
// Launch picker to choose photo for selected contact
final Intent intent = getPhotoPickIntent();
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.photoPickerNotFoundText1,
Toast.LENGTH_LONG).show();
}
}
// 封装请求Gallery的intent
public static Intent getPhotoPickIntent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
return intent;
}
// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
final Bitmap photo = data.getParcelableExtra("data");
// 下面就是显示照片了
System.out.println(photo);
//缓存用户选择的图片
img = getBitmapByte(photo);
mEditor.setPhotoBitmap(photo);
System.out.println("set new photo");
break;
}
case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
doCropPhoto(mCurrentPhotoFile);
break;
}
}
}
protected void doCropPhoto(File f) {
try {
// 启动gallery去剪辑这个照片
final Intent intent = getCropImageIntent(Uri.fromFile(f));
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
} catch (Exception e) {
Toast.makeText(this, R.string.photoPickerNotFoundText,
Toast.LENGTH_LONG).show();
}
}
/**
* Constructs an intent for image cropping. 调用图片剪辑程序
*/
public static Intent getCropImageIntent(Uri photoUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoUri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
return intent;
}
❸ 如何调用android的拍照或本地相册选取,然后再实现相片上传服务器
首先是拍照:使用Intent即可,
[java] view plainprint?
01.final String start = Environment.getExternalStorageState();
02.private static final String PHOTOPATH = "/photo/";
03.
04.if(start.equals(Environment.MEDIA_MOUNTED)){
05.Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
06.File file = new File(Environment.getExternalStorageDirectory()+PHOTOPATH);
07.if(!file.exists()){
08.file.mkdirs();
09.}
10.tempphontname = System.currentTimeMillis()+".jpg";
11.buffer.append(Environment.getExternalStorageDirectory()+PHOTOPATH).append(tempphontname);
12.intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(buffer.toString())));
13.startActivityForResult(intent, 1);
14.}
final String start = Environment.getExternalStorageState();
private static final String PHOTOPATH = "/photo/";
if(start.equals(Environment.MEDIA_MOUNTED)){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+PHOTOPATH);
if(!file.exists()){
file.mkdirs();
}
tempphontname = System.currentTimeMillis()+".jpg";
buffer.append(Environment.getExternalStorageDirectory()+PHOTOPATH).append(tempphontname);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(buffer.toString())));
startActivityForResult(intent, 1);
}
其次是从本地相册选:依旧是Intent.
如下代码:
[java] view plainprint?
01.if(start.equals(Environment.MEDIA_MOUNTED)){
02. Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
03. getImage.addCategory(Intent.CATEGORY_OPENABLE);
04. getImage.setType("image/jpeg");
05. startActivityForResult(getImage, 0);
06.}
if(start.equals(Environment.MEDIA_MOUNTED)){
Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
getImage.addCategory(Intent.CATEGORY_OPENABLE);
getImage.setType("image/jpeg");
startActivityForResult(getImage, 0);
}
接下来是主要的:因为调用完系统的方法后,回返回到回调方法onActivityResult(int, int, Intent)中,
在里面进行主要的照片上传服务器的操作,
见代码:
[java] view plainprint?
01.@Override
02. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
03. ContentResolver resolver = getContentResolver();
04. if(requestCode==1)//
05. {
06. if(resultCode==Activity.RESULT_OK)
07. {
08. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
09. {
10.ew Thread(new Runnable()
11. {
12. @Override
13. public void run() {
14.//进行上传操作
15.}
16.}.start();
转载
❹ Android拍照和选择相册图片上传为什么不清晰
压缩算法的问题,不知道是你自己写还是用其他产商的apk,
压缩过头了,导致清晰度下降了。
还有就是有些手机拍完照,本身有一定的压缩处理,所以再进行压缩就更小了,更模糊了。
这个就是手机要做适配处理。
❺ Android10以上拍照和选择相册适配以及向下兼容适配
最近一直被Android10相关的适配搞得焦头烂额,之前也听说过android10中的所有的视频,音频以及图片等资源为了统一的管理,统一放在一个共有的文件下,也就是所谓的沙箱。看了一下其他人写的文章,也提供了一种简单粗暴的方式也就是在清单文件application下配置#android:requestLegacyExternalStorage="true"#,但如果android11出来又得适配了,android11是禁止除了共有文件夹下新建视频,音频以及图片等文件。不然就会报找不到文件相关的错误,好了说到底我们还是得花点时间去适配android10以上的沙箱适配。
进入正题,接下来我们就来适配Android10相关的拍照以及选择相册并兼容android10以下的绝大部分的适配。
进入系统相册的操作都是一样的这里就不赘述:
主要的还是要对返回的data进行处理,也就是把uri转换成文件File的路径path
当然了拍照和位图Bitmap相关的适配是一样的。
7.0以上Android版本的路径配置
第一步
@xml/file_camera_paths 文件配置
拍照首先需要申请拍照权限
申请完后调用camera就可以拍照,拍照主要就是在调用相机的时需要自己去配置文件存储路径。
回调处理这里我就不赘述了 主要是对Android10以上关于图片配置相关的处理
既然关于Android 10那么我们也讲一下关于定位方面的适配,Android10以上需要在清淡文件中添加一个新的定位权限
❻ Android 使用系统相机拍照和读取相册照片
1.拍照 (对于7.0以上的版本,不在允许直接访问uri)
`
若不指定输出路径intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity)); 在onActivityResult()中,通过
`
可以拿到uri,但获得的图片是被压缩过的。若指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);输出路径,则此处的intent为null,但可以使用我们存的uri读取照片,此时的照片没有被压缩。
2.从相册中读取照片, 方法:
`
`
即使设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity));输出路径,仍然不能从此路径中读取,只能在onActivityForResult()中通过event.uri = intent.getData();方式获得图片uri。
此种现象也好理解,拍照时产生新的图片,自然可根据设置的uri进行图片保存,而读取相册时,图片已经在目录中不能转移到自己设定的uri中。
Androidmanifest.xml中
`
在 res/xml/provider_paths.xml
`
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="JDTobs" path=""/>
<files-path name="name" path="path" />
<cache-path name="name" path="path" /> <external-path name="name" path="path" />
<external-files-path name="name" path="path" />
<external-cache-path name="name" path="path" /> </paths> `
读取uri
❼ Android开发如何从手机相册中选择照片
File DatalDir = Environment.getExternalStorageDirectory();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss",
Locale.SIMPLIFIED_CHINESE);
String midPath = "DCIM/Camera/"+ sdf.format(new Date())+ ".jpg";
File outMid = new File( DatalDir.getPath() + "/DCIM/Camera");
存这个地址就可以;
❽ 【基础笔记】Android Studio拍照、选择相册(第三方框架)
①选择指定后缀文件
②在图片选择器中选择图片或视频
③接受返回的文件
FilePicker
①、添加依赖
②、Activity实现takephoto
③实例图片
④Git地址
TakePhoto
❾ Android WebView 调用系统拍照和相册
由于业务需要,APP内嵌H5,需要调去系统相册和拍照,网上找了点资料,整理一下,供大家参考:
private static final int REQUEST_CAMERA =1;
private static final int REQUEST_CHOOSE =2;
private ValueCallbackmUploadMessage;
private ;
private UricameraUri;
//5.0以后的方法
webView.setWebChromeClient(new WebChromeClient() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
if (mUploadMessagesAboveL !=null) {
mUploadMessagesAboveL.onReceiveValue(null);
mUploadMessagesAboveL =null;
}else {
mUploadMessagesAboveL = filePathCallback;
selectImage();
}
return true;
}
});
//选择图片和拍照,对应的string文件,可以自己写死:拍照,相册,取消
private void selectImage() {
ActionSheet.createBuilder(this, getSupportFragmentManager()).
setOtherButtonTitles(new String[]{getResources().getString(R.string.common_tip_photos), getResources().getString(R.string.common_picture)}).
setCancelButtonTitle(getResources().getString(R.string.common_cancel)).setCancelableOnTouchOutside(true).setListener(new ActionSheet.ActionSheetListener() {
public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
if (mUploadMessage !=null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage =null;
}
if (mUploadMessagesAboveL !=null) {
mUploadMessagesAboveL.onReceiveValue(null);
mUploadMessagesAboveL =null;
}
actionSheet.dismiss();
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
switch (index) {
case 0:
chosePicture();
break;
case 1:
setRequestCamera();
}
}
}).show();
}
//拍照,添加权限申请 这个可以自己写下,我这边是项目中写好的,直接拿过来用了
public void setRequestCamera() {
permissionsBuilder =new YXTPermissionsBuilder.Builder(this)
.setOnGrantedListener((requestCode, perms) -> {
openCamera();
})
.setRationale4NeverAskAgain(LanguageUtils.isEnglish() ? String.format(getString(R.string.permission_tips), getString(R.string.common_camera), getString(R.string.app_name), getString(R.string.app_name)) :
String.format(getString(R.string.permission_tips), getString(R.string.app_name), getString(R.string.common_camera), getString(R.string.app_name)))
//必需
.setRequestCode(ConstantsData.GET_CAMERA)
.build();
permissionsBuilder.requestPermissions(Manifest.permission.CAMERA);
}
/**
* 本地相册选择图片
*/
private void chosePicture() {
Intent innerIntent =new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, null);
startActivityForResult(wrapperIntent, REQUEST_CHOOSE);
}
/**
* 打开照相机
*/
private void openCamera() {
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imagePaths = Environment.getExternalStorageDirectory().getPath() +"/pbccrc/Images/" + (System.currentTimeMillis() +".jpg");
// 必须确保文件夹路径存在,否则拍照后无法完成回调
File vFile =new File(imagePaths);
if (!vFile.exists()) {
File vDirPath = vFile.getParentFile();
vDirPath.mkdirs();
}else {
if (vFile.exists()) {
vFile.delete();
}
}
cameraUri = FileProvider.getUriForFile(
this,
getPackageName() +".fileprovider",
vFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
/**
* 选择照片后结束
*
* @param data
*/
private UriafterChosePic(Intent data) {
if (data !=null) {
final String path = data.getData().getPath();
if (path !=null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
return data.getData();
}else {
Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
}
}
return null;
}
/**
* 返回文件选择
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (mUploadMessagesAboveL !=null) {
onActivityResultAboveL(requestCode, resultCode, intent);
}
if (mUploadMessage ==null)return;
Uri uri =null;
if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {
uri =cameraUri;
Log.e("onActivityResult: " + uri.toString());
}
if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {
uri = afterChosePic(intent);
}
mUploadMessage.onReceiveValue(uri);
mUploadMessage =null;
super.onActivityResult(requestCode, resultCode, intent);
}
/**
* 5.0以后机型 返回文件选择
*
* @param requestCode
* @param resultCode
* @param data
*/
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
Uri[] results =null;
if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {
results =new Uri[]{cameraUri};
}
if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {
if (data !=null) {
String dataString = data.getDataString();
if (dataString !=null)
results =new Uri[]{Uri.parse(dataString)};
}
}
mUploadMessagesAboveL.onReceiveValue(results);
mUploadMessagesAboveL =null;
return;
}
基本都可以拿去用了,希望有帮助