android拍照代码
❶ 如何调用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 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;
}
基本都可以拿去用了,希望有帮助
❸ android开发怎么实现拍照上传
这个其实是一个很泛的问题
我大致说下我的思路:
用startactivityforresult方法调用系统的摄像头,随便拍张照片,把照片保存在某一目录下面
点击完成后,会在onactivityresult中,根据目录的地址,再把这目录下面的资源得转换为文件,接着通过接口进行提交。提交成功后,后台返回一个URL。
通过这个URL,运用imageload(第三方插件)显示图片
❹ 怎么调用android的摄像头拍照
我们要调用摄像头的拍照功能,显然
第一步必须加入调用摄像头硬件的权限,拍完照后我们要将图片保存在SD卡中,必须加入SD卡读写权限,所以第一步,我们应该在Android清单文件中加入以下代码
<uses-permission android:name="android.permission.CAMERA"/>//摄像头权限
SD卡读写权限
<uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
第二步,要将摄像头捕获的图像实时地显示在手机上。
我们是用SurfaceView这个视图组件来实现的,因此在main.xml中加入下列代码
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/surfaceview"
/>
第三步,设置窗口的显示方式
首先获得当前窗口Windowwindow = getWindow();//得到窗口
接着设置没有标题requestWindowFeature(Window.FEATURE_NO_TITLE);//没有标题
接着设置全屏 window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
当然,我们在拍照过程中,屏幕必须一致处于高亮状态,因此接着加入下面代码
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置高亮
至此,我们将窗口的显示方式规定死了,然后才能设置窗口上显示的组件(顺序非常重要)
setContentView(R.layout.main);
第四步,设置SurficeView显示控件的属性
找到surficeView
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
设置它的像素为800x600
surfaceView.getHolder().setFixedSize(800,480);
//下面设置surfaceView不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前
surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
第五步,就是为surficeView加入回调方法(callBack)
surfaceView.getHolder().addCallback(newSurfaceCallback());
上面的回调类是我们自己定义的,代码如下
private class SurfaceCallback implementsSurfaceHolder.Callback{
@Override
public void surfaceCreated(SurfaceHolderholder) {
try {
camera = Camera.open();//打开硬件摄像头,这里导包得时候一定要注意是android.hardware.Camera
WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);//得到窗口管理器
Display display = wm.getDefaultDisplay();//得到当前屏幕
Camera.Parameters parameters =camera.getParameters();//得到摄像头的参数
parameters.setPreviewSize(display.getWidth(),display.getHeight());//设置预览照片的大小
parameters.setPreviewFrameRate(3);//设置每秒3帧
parameters.setPictureFormat(PixelFormat.JPEG);//设置照片的格式
parameters.setJpegQuality(85);//设置照片的质量
parameters.setPictureSize(display.getHeight(),display.getWidth());//设置照片的大小,默认是和屏幕一样大
camera.setParameters(parameters);
camera.setPreviewDisplay(surfaceView.getHolder());//通过SurfaceView显示取景画面
camera.startPreview();//开始预览
isPreview = true;//设置是否预览参数为真
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
@Override
public void surfaceChanged(SurfaceHolderholder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolderholder) {
if(camera!=null){
if(isPreview){//如果正在预览
camera.stopPreview();
camera.release();
}
}
}
}
第六步,我们必须对按键事件进行监听,如是拍照还是聚焦,代码如下
public boolean onKeyDown(int keyCode,KeyEvent event) {//处理按键事件
if(camera!=null&&event.getRepeatCount()==0)//代表只按了一下
{
switch(keyCode){
case KeyEvent.KEYCODE_BACK://如果是搜索键
camera.autoFocus(null);//自动对焦
break;
case KeyEvent.KEYCODE_DPAD_CENTER://如果是中间键
camera.takePicture(null, null, new TakePictureCallback());//将拍到的照片给第三个对象中,这里的TakePictureCallback()是自己定义的,在下面的代码中
break;
}
}
return true;//阻止事件往下传递,否则按搜索键会变成系统默认的
}
------------------------------------------------------------------------------------------
private final class TakePictureCallbackimplements PictureCallback{
public void onPictureTaken(byte[] data,Camera camera) {
try {
Bitmap bitmap =BitmapFactory.decodeByteArray(data, 0, data.length);
File file = newFile(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
FileOutputStream outputStream = newFileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100,outputStream);
outputStream.close();
camera.stopPreview();
camera.startPreview();//处理完数据之后可以预览
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
注意,代码中有两个回调类,一个是SurfaceCallback(),另外一个是TakePictureCallback(),初学者可能一时难以理解,通俗地讲,前者是用来监视surficeView这个暂时存放图片数据的显示控件的,根据它的显示情况调用不同的方法,包括surfaceCreated(),surfaceChanged(),surfaceDestroyed(),也就不难理解为什么会有这三个回调方法了(注意,在surfaceDestroyed()方法中必须释放摄像头,详细代码参见上方)。TakePictureCallback()是为了监视是否拍照而设计的接口,期中也仅有一个方法,camera将拍照得到的数据传入方法,我们便可以对拍照得到的数据进行进一步处理
❺ 如何在android中后台开启摄像头默默拍照
(1)CameraActivity.java
package com.camera.test;import android.app.Activity;import android.content.pm.ActivityInfo;import android.os.Bundle;import android.view.Window;import android.view.WindowManager;import android.widget.RelativeLayout;public class CameraActivity extends Activity {private CameraView view;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置横屏模式以及全屏模式view = new CameraView(this);// 通过一个surfaceview的view来实现拍照view.setId(1);view = new CameraView(this, this);setContentView(R.layout.camera_layout);RelativeLayout relative = (RelativeLayout) this.findViewById(R.id.ly);RelativeLayout.LayoutParams Layout = new RelativeLayout.LayoutParams(3, 3);// 设置surfaceview使其满足需求无法观看预览Layout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);Layout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);relative.addView(view, Layout);}}(2) CameraView.javapackage com.camera.test;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Point;import android.graphics.PointF;import android.hardware.Camera;import android.hardware.Camera.AutoFocusCallback;import android.hardware.Camera.ShutterCallback;import android.media.AudioManager;import android.media.FaceDetector;import android.media.FaceDetector.Face;import android.os.Environment;import android.os.Handler;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.widget.Toast;public class CameraView extends SurfaceView implements SurfaceHolder.Callback,Camera.PictureCallback{private SurfaceHolder holder;private Camera camera;private Camera.Parameters parameters;private Activity act;private Handler handler = new Handler();private Context context;private SurfaceView surfaceView;private AudioManager audio;private int current;public CameraView(Context context) {super(context);surfaceView = this;audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);final int current = audio.getRingerMode();audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);this.context = context;holder = getHolder();// 生成Surface Holderholder.addCallback(this);holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// 指定Push Bufferhandler.postDelayed(new Runnable() {@Overridepublic void run() {if (camera == null) {handler.postDelayed(this, 1 * 1000);// 由于启动camera需要时间,在此让其等两秒再进行聚焦知道camera不为空} else {camera.autoFocus(new AutoFocusCallback() {@Overridepublic void onAutoFocus(boolean success, Camera camera) {if (success) {camera.takePicture(new ShutterCallback() {// 如果聚焦成功则进行拍照@Overridepublic void onShutter() {}}, null, CameraView.this);} else {}}});}}}, 2 * 1000);}public CameraView(Context context, Activity act) {// 在此定义一个构造方法用于拍照过后把CameraActivity给finish掉this(context);this.act = act;}@Overridepublic void surfaceCreated(final SurfaceHolder holder) {// TODO Auto-generated method stubcamera = Camera.open();// 摄像头的初始化handler.postDelayed(new Runnable() {@Overridepublic void run() {if (holder != null) {try {camera.setPreviewDisplay(holder);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {handler.postDelayed(this, 1 * 1000);}}}, 2 * 1000);}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {// TODO Auto-generated method stubparameters = camera.getParameters();camera.setParameters(parameters);// 设置参数camera.startPreview();// 开始预览}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {// TODO Auto-generated method stub}public void onPictureTaken(byte[] data, Camera camera) {// 拍摄完成后保存照片try {Date date = new Date();SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");String time = format.format(date);//在SD卡上创建文件夹File file = new File(Environment.getExternalStorageDirectory()+ "/myCamera/pic");if (!file.exists()) {file.mkdirs();}String path = Environment.getExternalStorageDirectory()+ "/myCamera/pic/" + time + ".jpg";data2file(data, path);camera.setPreviewCallback(null);camera.stopPreview();camera.release();camera = null;holder.removeCallback(CameraView.this);audio.setRingerMode(current);act.finish();//uploadFile(path);} catch (Exception e) {}}private void data2file(byte[] w, String fileName) throws Exception {// 将二进制数据转换为文件的函数FileOutputStream out = null;try {out = new FileOutputStream(fileName);out.write(w);out.close();} catch (Exception e) {if (out != null)out.close();throw e;}}// private void uploadFile(String filePath)// 拍照过后上传文件到服务器// {// }}
❻ 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手机的拍照功能
public class testActivity extends Activity {
public static final int NONE = 0;
public static final int PHOTOHRAPH = 1;// 拍照
public static final int PHOTOZOOM = 2; // 缩放
public static final int PHOTORESOULT = 3;// 结果
public static final String IMAGE_UNSPECIFIED = "image/*";
ImageView imageView = null;
Button button0 = null;
Button button1 = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageID);
button0 = (Button) findViewById(R.id.btn_01);
button1 = (Button) findViewById(R.id.btn_02);
button0.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
startActivityForResult(intent, PHOTOZOOM);
}
});
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
startActivityForResult(intent, PHOTOHRAPH);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == NONE)
return;
// 拍照
if (requestCode == PHOTOHRAPH) {
//设置文件保存路径这里放在跟目录下
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
startPhotoZoom(Uri.fromFile(picture));
}
if (data == null)
return;
// 读取相册缩放图片
if (requestCode == PHOTOZOOM) {
startPhotoZoom(data.getData());
}
// 处理结果
if (requestCode == PHOTORESOULT) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件
imageView.setImageBitmap(photo);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 64);
intent.putExtra("outputY", 64);
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTORESOULT);
}
}
❽ android 用AlertDialog启用相机权限的代码怎么写啊
/**
* @Description 调用系统相机照相,获取原图像
* @param activity 就是你的mainactivity
* @param dir 拍照后保存在本地的图片路径
* @param filename 图片的名称
* @param cmd 返回的requestCode
* @return void
*/
public static boolean takePhoto(final Activity activity, final String dir,
final String filename, final int cmd) {
String filePath = dir + filename;
// final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Log.d("test", "MediaStore.ACTION_IMAGE_CAPTURE"
+ android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE == null ? "android.media.action.IMAGE_CAPTURE"
: android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final File cameraDir = new File(dir);
if (!cameraDir.exists()) {
// return false;
cameraDir.mkdirs();
}
final File file = new File(filePath);
final Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
try {
activity.startActivityForResult(intent, cmd);
} catch (final ActivityNotFoundException e) {
return false;
}
return true;
}
然后在你的onactivityforresult方法里写:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PHOTOGRAPH://拍照
if (resultCode == RESULT_OK) {
String url = FileHelper.Get_SDCardPath() + Constant.HHXH_IMGDIR
+ BitmapUtil.tempPhoto;//图片路径,和你前面调用相册时设的路径一样
Bitmap bitmap = BitmapUtil
.extractThumbNail(url, 480, 320, true);//这里是根据本地路径获取图片并压缩的,这个我写的代码比较多就不上传了
findviewbyid(R.id.imgPhoto).setImageBitmap(bitmap);
}
}
}