典型的使用场景就是要设置一个头像,头像需要从系统图库或者拍照获得,在android4.4之前,我用的代码没问题,但是今天使用android4.4的时候突然发现不灵了。baidu了一圈,终于解决了。
下面是解决方案:
1.privateString[] items =newString[] {"图库","拍照"};
2./*头像名称*/
3.privatestaticfinalString IMAGE_FILE_NAME ="face.jpg";
4./*请求码*/
5.privatestaticfinalintIMAGE_REQUEST_CODE =0;
6.privatestaticfinalintSELECT_PIC_KITKAT =3;
7.privatestaticfinalintCAMERA_REQUEST_CODE =1;
8.privatestaticfinalintRESULT_REQUEST_CODE =2;
9.
10.privatevoidshowSettingFaceDialog() {
11.
12.newAlertDialog.Builder(this)
13..setTitle("图片来源")
14..setCancelable(true)
15..setItems(items,newDialogInterface.OnClickListener() {
16.
17.@Override
18.publicvoidonClick(DialogInterface dialog,intwhich) {
19.switch(which) {
20.case0:// Local Image
21.Intent intent=newIntent(Intent.ACTION_GET_CONTENT);
22.intent.addCategory(Intent.CATEGORY_OPENABLE);
23.intent.setType("image/*");
24.if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
25.startActivityForResult(intent,SELECT_PIC_KITKAT);
26.}else{
27.startActivityForResult(intent,IMAGE_REQUEST_CODE);
28.}
29.break;
30.case1:// Take Picture
31.Intent intentFromCapture =newIntent(
32.MediaStore.ACTION_IMAGE_CAPTURE);
33.//判断存储卡是否可以用,可用进行存储
34.if(hasSdcard()) {
35.intentFromCapture.putExtra(
36.MediaStore.EXTRA_OUTPUT,
37.Uri.fromFile(newFile(Environment
38..getExternalStorageDirectory(),
39.IMAGE_FILE_NAME)));
40.}
41.startActivityForResult(intentFromCapture,
42.CAMERA_REQUEST_CODE);
43.break;
44.}
45.}
46.})
47..setNegativeButton("取消",
48.newDialogInterface.OnClickListener() {
49.
50.@Override
51.publicvoidonClick(DialogInterface dialog,
52.intwhich) {
53.dialog.dismiss();
54.}
55.}).show();
56.
57.}
58.
59.@Override
60.protectedvoidonActivityResult(intrequestCode,intresultCode, Intent data) {
61.//结果码不等于取消时候
62.if(resultCode != RESULT_CANCELED) {
63.switch(requestCode) {
64.caseIMAGE_REQUEST_CODE:
65.startPhotoZoom(data.getData());
66.break;
67.caseSELECT_PIC_KITKAT:
68.startPhotoZoom(data.getData());
69.break;
70.caseCAMERA_REQUEST_CODE:
71.if(hasSdcard()) {
72.File tempFile =newFile(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
73.startPhotoZoom(Uri.fromFile(tempFile));
74.}else{
75.ToastUtils.showShort(context,"未找到存储卡,无法存储照片!");
76.}
77.
78.break;
79.caseRESULT_REQUEST_CODE:
80.if(data !=null) {
81.setImageToView(data,iv_face);
82.}
83.break;
84.}
85.}
86.super.onActivityResult(requestCode, resultCode, data);
87.}
88.
89./**
90.*裁剪图片方法实现
91.*
92.*@paramuri
93.*/
94.publicvoidstartPhotoZoom(Uri uri) {
95.if(uri ==null) {
96.Log.i("tag","The uri is not exist.");
97.return;
98.}
99.
100.Intent intent =newIntent("com.android.camera.action.CROP");
101.if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
102.String url=getPath(context,uri);
103.intent.setDataAndType(Uri.fromFile(newFile(url)),"image/*");
104.}else{
105.intent.setDataAndType(uri,"image/*");
106.}
107.
108.//设置裁剪
109.intent.putExtra("crop","true");
110.// aspectX aspectY是宽高的比例
111.intent.putExtra("aspectX",1);
112.intent.putExtra("aspectY",1);
113.// outputX outputY是裁剪图片宽高
114.intent.putExtra("outputX",200);
115.intent.putExtra("outputY",200);
116.intent.putExtra("return-data",true);
117.startActivityForResult(intent, RESULT_REQUEST_CODE);
118.}
119.
120./**
121.*保存裁剪之后的图片数据
122.*
123.*@parampicdata
124.*/
125.privatevoidsetImageToView(Intent data,ImageView imageView) {
126.Bundle extras = data.getExtras();
127.if(extras !=null) {
128.Bitmap photo = extras.getParcelable("data");
129.Bitmap roundBitmap=ImageUtil.toRoundBitmap(photo);
130.imageView.setImageBitmap(roundBitmap);
131.saveBitmap(photo);
132.}
133.}
134.
135.publicvoidsaveBitmap(Bitmap mBitmap) {
136.File f =newFile(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
137.try{
138.f.createNewFile();
139.FileOutputStream fOut =null;
140.fOut =newFileOutputStream(f);
141.mBitmap.compress(Bitmap.CompressFormat.JPEG,100, fOut);
142.fOut.flush();
143.fOut.close();
144.}catch(FileNotFoundException e) {
145.e.printStackTrace();
146.}catch(IOException e) {
147.e.printStackTrace();
148.}
149.}
150.
151.
152.//以下是关键,原本uri返回的是file:///...来着的,android4.4返回的是content:///...
153.@SuppressLint("NewApi")
154.publicstaticString getPath(finalContext context,finalUri uri) {
155.
156.finalbooleanisKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
157.
158.// DocumentProvider
159.if(isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
160.// ExternalStorageProvider
161.if(isExternalStorageDocument(uri)) {
162.finalString docId = DocumentsContract.getDocumentId(uri);
163.finalString[] split = docId.split(":");
164.finalString type = split[0];
165.
166.if("primary".equalsIgnoreCase(type)) {
167.returnEnvironment.getExternalStorageDirectory() +"/"+ split[1];
168.}
169.
170.}
171.// DownloadsProvider
172.elseif(isDownloadsDocument(uri)) {
173.finalString id = DocumentsContract.getDocumentId(uri);
174.finalUri contentUri = ContentUris.withAppendedId(
175.Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
176.
177.returngetDataColumn(context, contentUri,null,null);
178.}
179.// MediaProvider
180.elseif(isMediaDocument(uri)) {
181.finalString docId = DocumentsContract.getDocumentId(uri);
182.finalString[] split = docId.split(":");
183.finalString type = split[0];
184.
185.Uri contentUri =null;
186.if("image".equals(type)) {
187.contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
188.}elseif("video".equals(type)) {
189.contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
190.}elseif("audio".equals(type)) {
191.contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
192.}
193.
194.finalString selection ="_id=?";
195.finalString[] selectionArgs =newString[] {
196.split[1]
197.};
198.
199.returngetDataColumn(context, contentUri, selection, selectionArgs);
200.}
201.}
202.// MediaStore (and general)
203.elseif("content".equalsIgnoreCase(uri.getScheme())) {
204.// Return the remote address
205.if(isGooglePhotosUri(uri))
206.returnuri.getLastPathSegment();
207.
208.returngetDataColumn(context, uri,null,null);
209.}
210.// File
211.elseif("file".equalsIgnoreCase(uri.getScheme())) {
212.returnuri.getPath();
213.}
214.
215.returnnull;
216.}
217.
218./**
219.* Get the value of the data column for this Uri. This is useful for
220.* MediaStore Uris, and other file-based ContentProviders.
221.*
222.* @param context The context.
223.* @param uri The Uri to query.
224.* @param selection (Optional) Filter used in the query.
225.* @param selectionArgs (Optional) Selection arguments used in the query.
226.* @return The value of the _data column, which is typically a file path.
227.*/
228.publicstaticString getDataColumn(Context context, Uri uri, String selection,
229.String[] selectionArgs) {
230.
231.Cursor cursor =null;
232.finalString column ="_data";
233.finalString[] projection = {
234.column
235.};
236.
237.try{
238.cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
239.null);
240.if(cursor !=null&& cursor.moveToFirst()) {
241.finalintindex = cursor.getColumnIndexOrThrow(column);
242.returncursor.getString(index);
243.}
244.}finally{
245.if(cursor !=null)
246.cursor.close();
247.}
248.returnnull;
249.}
250.
251.
252./**
253.* @param uri The Uri to check.
254.* @return Whether the Uri authority is ExternalStorageProvider.
255.*/
256.publicstaticbooleanisExternalStorageDocument(Uri uri) {
257.return"com.android.externalstorage.documents".equals(uri.getAuthority());
258.}
259.
260./**
261.* @param uri The Uri to check.
262.* @return Whether the Uri authority is DownloadsProvider.
263.*/
264.publicstaticbooleanisDownloadsDocument(Uri uri) {
265.return"com.android.providers.downloads.documents".equals(uri.getAuthority());
266.}
267.
268./**
269.* @param uri The Uri to check.
270.* @return Whether the Uri authority is MediaProvider.
271.*/
272.publicstaticbooleanisMediaDocument(Uri uri) {
273.return"com.android.providers.media.documents".equals(uri.getAuthority());
274.}
275.
276./**
277.* @param uri The Uri to check.
278.* @return Whether the Uri authority is Google Photos.
279.*/
280.publicstaticbooleanisGooglePhotosUri(Uri uri) {
281.return"com.google.android.apps.photos.content".equals(uri.getAuthority());
282.}
最后只需要在需要的地方调用showSettingFaceDialog()就可以了。
如果要获得剪裁的图片保存路径,然后上传,我这边是这样处理的(这里每个人的写法不一样):
但只要获得filePath就可以根据自己的需求处理了
1.privatevoiduploadFace(){
2.File file =newFile(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
3.String filePath=file.getAbsolutePath();
4.
5.Log.i("tag","filePath="+filePath);
6.HttpHelper.uploadFileWithConcatUrl(context,HttpHelper.UPDATE_USER_ICON,App.user.getUser_session_key() ,filePath ,newHttpHelper.OnFileUploadListener(){
7.
8.@Override
9.publicvoidonFileUploadSuccess(String orignUrl, String midImgUrl,
10.String smallImgUrl) {
11.// TODO Auto-generated method stub
12.
13.App.user.setHead_icon(orignUrl);
14.
15.saveUser();
16.}
17.
18.});
19.}
网友评论