近来项目人手紧缺,发挥社会主义螺丝精神,加入了android APP开发。初学的我,连调用相机也不知道用什么方法,只得上网找老师了。万幸,网络上的大牛非常多,找了一篇博客,方法拿过来就可用,自己整理一个,就变成私有的了 。不用看其他地方的代码,只要要看调用相应拍照和裁剪的方法即可,由于是从项目中复制的代码,编译多少会有些问题,但编译问题都不问题。
/**
* 初始化
*/
public void init()
{
String sdStatus = Environment.getExternalStorageState();
// 检测sd是否可用
if (!sdStatus.equals(Environment.MEDIA_MOUNTED))
{
showMessage("SD卡不可用");
return;
}
File pictureFileDir = new File(
Environment.getExternalStorageDirectory(), "/home");
if (!pictureFileDir.exists())
{
pictureFileDir.mkdirs();
}
picFile = new File(pictureFileDir, "upload.jpeg");
if (!picFile.exists())
{
try
{
picFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
photoUri = Uri.fromFile(picFile);
}
/**
* 初始化页面元素
*/
public void initView()
{
Log.i(TAG, "initView");
ivHeadURL = (ImageView) mRootView.findViewById(R.id.iv_head_portrait);
ImageLoader.getInstance().displayImage(GlobalConstants.getAccountInfo().getHeadURL(), ivHeadURL,imageOptions);
}
/**
* 注册监听器,并处理事件
*/
private void initListener()
{
// 编辑头像
ivHeadPortrait.setOnClickListener((OnClickListener) this);
}
/**
* 处理点击事件
*/
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Bundle data = new Bundle();
switch (v.getId())
{
case R.id.rl_head_portrait:
doPickPhotoAction();
break;
default:
Log.d(TAG, "未知操作");
break;
}
}
/**
* 处理INTENT返回结果
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.e("LM", "resultCode:" + resultCode);
if (resultCode !=Activity.RESULT_OK)
{
return;
}
switch (requestCode)
{
//拍完照片后,开始裁剪图片
case activity_result_camara_with_data: /
try
{
cropImageUriByTakePhoto();
}
catch (Exception e)
{
e.printStackTrace();
}
break;
//裁剪完图片后,上传图片
case activity_result_cropimage_with_data:
try
{
mWaitDialog.show("正在上传");
Log.i(TAG, "uploading");
if (photoUri != null)
{
new Thread()
{
@Override
public void run()
{
// TODO Auto-generated method stub
super.run();
Log.d(TAG, "photoUri.getPath():" + photoUri.getPath());
uploadAvatar(photoUri.getPath());
}
}.start();
}
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
/**
* 选择拍照或者选择本地图片
*/
private void doPickPhotoAction()
{
final Context dialogContext = new ContextThemeWrapper(mContext,
android.R.style.Theme_Light);
String cancel = "返回";
String[] choices;
choices = new String[2];
choices[0] = "拍照"; // 条目一
choices[1] = "选择本地图片"; // 条目二
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("上传头像");
builder.setSingleChoiceItems(adapter,
-1,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
switch (which)
{
case 0:
String status = Environment.getExternalStorageState();
// SD卡可用
if (status.equals(Environment.MEDIA_MOUNTED))
{
//拍照
doTakePhoto();
}
break;
case 1:
//裁剪
doCropPhoto();
break;
}
}
});
builder.setNegativeButton(cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
builder.create().show();
}
/**
* 拍照
*/
protected void doTakePhoto()
{
try
{
//如果photoUri为null,当作SD卡不可用处理
if (photoUri == null)
{
showMessage("SD卡不可用");
return;
}
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//设定要将照片保存到photoUri
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//拍照,并设定请求码
((Activity) mContext).startActivityForResult(cameraIntent,
activity_result_camara_with_data);
}
catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
}
/**
* 裁剪(在拍完照片后,处理intent返回结果时调用。)
*/
private void cropImageUriByTakePhoto()
{
//如果photoUri为null,当作SD卡不可用处理
if (photoUri == null)
{
showMessage("SD卡不可用");
return;
}
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", GlobalConstants.HeadSize.w);
intent.putExtra("outputY", GlobalConstants.HeadSize.h);
intent.putExtra("scale", true);
//设定要将照片保存到photoUri(对同一个文件读写?内存)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.putExtra("return-data", false);
//设定返回格式
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true); // no face detection
((Activity) mContext).startActivityForResult(intent,
activity_result_cropimage_with_data);
}
/**
* 选择图片并进行裁剪,保存裁剪后的图片
*/
protected void doCropPhoto()
{
//如果photoUri为null,当作SD卡不可用处理
if (photoUri == null)
{
showMessage("SD卡不可用");
return;
}
try
{
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", GlobalConstants.HeadSize.w);
intent.putExtra("outputY", GlobalConstants.HeadSize.h);
intent.putExtra("noFaceDetection", true);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
//设定要将照片保存到photoUri(对同一个文件读写?内存)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
//选择图片并裁剪,设定请求码
((Activity) mContext).startActivityForResult(intent,
activity_result_cropimage_with_data);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 解码图片
*/
private Bitmap decodeUriAsBitmap(Uri uri)
{
Bitmap bitmap = null;
try
{
bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
.openInputStream(uri));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
return bitmap;
}
/**
* 上传图片
*/
private void uploadAvatar(String path)
{
Log.i(TAG, "UPLOAD");
String ret = null;
File file = new File(path);
if (!file.exists())
{
return;
}
try
{
String split = "--";
String end = "\r\n";
String name = "avatar";
String boundary = UUID.randomUUID().toString();
String token = GlobalConstants.getAccountInfo().getToken();
String url = "http://xxx/upload/uploadAvatar.do?access_token=" + token;
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data;;boundary=" + boundary);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(file));
StringBuilder sb = new StringBuilder();
sb.append(split);
sb.append(boundary);
sb.append(end);
sb.append("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + file.getName() + "\"" + end);
sb.append("Content-Type: image/gif;" + end);
sb.append(end);
System.out.println(sb);
out.write(sb.toString().getBytes());
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1)
{
out.write(bufferOut, 0, bytes);
}
out.write(end.getBytes());
out.write((split + boundary + split + end).getBytes());
in.close();
out.close();
int responCode = conn.getResponseCode();
Log.i(TAG, "responCode:" + responCode);
if (responCode == HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
StringBuffer sb2 = new StringBuffer();
int line;
while ((line = input.read()) != -1)
{
sb2.append((char) line);
}
ret = sb2.toString();
Log.i(TAG, "respon:" + ret);
JSONObject jsonObject = new JSONObject(ret);
int resultCode = jsonObject.getInt(GlobalConstants.NetKey.RESULT_CODE);
Log.i(TAG, "resultCode:" + resultCode);
if (0 == resultCode)
{
String data = jsonObject.getString("data");
JSONObject dataJson = new JSONObject(data);
String headURL = dataJson.getString("file_path");
Log.i(TAG, "HeadURL:" + headURL);
//上传成功,请求修改头像地址
AccountManager.getInstance().init(mContext);
AccountManager.getInstance().setAccountInfo(GlobalConstants.OptionType.SET_HEAD, headURL, new BaseCallback()
{
@Override
public void onResult(Object obj)
{
// TODO Auto-generated method stub
if (obj != null)
{
mHandler.sendEmptyMessage(HEAD_RESPON_SUCCESS);
}
}
@Override
public void onError(Object obj)
{
// TODO Auto-generated method stub
Result errInfo = (Result) obj;
showMessage(errInfo.getResultMsg());
mHandler.sendEmptyMessage(HEAD_RESPON_FAIL);
}
});
}
else
{
Log.e(TAG, "ERROR resultCode:" + resultCode);
mHandler.sendEmptyMessage(HEAD_RESPON_FAIL);
}
input.close();
}
else
{
Log.e(TAG, "ERROR responCode:" + responCode);
mHandler.sendEmptyMessage(HEAD_RESPON_FAIL);
}
conn.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}