从相册或拍照获取图片,并实现图片的裁剪
来源:互联网 发布:ubuntu 开3306端口 编辑:程序博客网 时间:2024/06/13 01:57
MainActivity:
package com.example.xushuailong.mydopicture;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.Drawable;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.v4.app.FragmentActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import com.example.xushuailong.mydopicture.utils.Utilty;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class MainActivity extends FragmentActivity implements View.OnClickListener { private static final int REQUEST_CODE_PICK_IMAGE = 0; private static final int REQUEST_CODE_CAPTURE_CAMERA = 1; private static final int REQUEST_CODE_REL_CAPTURE_CAMERA = 2; private static final int REQUEST_CODE_CROP_CAPTURE_CAMERA = 3;// private static final int REQUEST_CODE_CROP_PICK_IMAGE = 3; private Button btn_get_from_album, btn_get_from_camera, btn_get_rel_from_camera, btn_get_crop_from_camera, btn_get_crop_from_album; private String ima_path; private TextView txt_img_path; private ImageView img; private String rel_ima_path; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_PICK_IMAGE){ //相册 if (null != data) { Uri uri = data.getData(); Log.d("xsl", "image_uri:" + uri); String img_path = Utilty.getPathFromKitKat(getApplicationContext(), uri); todoImageWithPatn(img_path); } }else if (requestCode == REQUEST_CODE_CAPTURE_CAMERA) { //相机 if (null != data) { Uri uri = data.getData(); Log.d("xsl", "camera_uri:" + uri); if (uri == null) { Bundle bundle = data.getExtras(); if (bundle != null) { Bitmap photo = (Bitmap) bundle.get("data"); saveImage(photo, ima_path); } else { Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show(); } } else { //TODO do find the path of pic by uri } } }else if (requestCode == REQUEST_CODE_REL_CAPTURE_CAMERA){ if (null != data){ Log.d("xsl", "data_extra: " + data.getExtras()); }else { Log.d("xsl", "data is null !"); } todoImageWithPatn(rel_ima_path); }else if (requestCode == REQUEST_CODE_CROP_CAPTURE_CAMERA) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(Uri.fromFile(new File(rel_ima_path)), "image/*"); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(rel_ima_path))); startActivityForResult(intent, REQUEST_CODE_REL_CAPTURE_CAMERA); } } private void todoImageWithPatn(String ima_path) { txt_img_path.setText("path: " + ima_path);// img.setImageDrawable(Drawable.createFromPath(ima_path)); try { img.setImageDrawable(Drawable.createFromStream(new FileInputStream(ima_path),System.currentTimeMillis()+"ss.jpg")); } catch (Exception e) { e.printStackTrace(); } } private void saveImage(Bitmap photo, String ima_path) {// img.setImageBitmap(photo); File file = new File(ima_path); if (!file.exists()){ file.mkdirs(); } BufferedOutputStream out = null; try { file = new File(ima_path + File.separator + System.currentTimeMillis() +".jpg"); file.createNewFile(); out = new BufferedOutputStream(new FileOutputStream(file.getPath(),false)); Log.d("xsl","image_path: "+file.getPath()); photo.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); todoImageWithPatn(file.getPath()); } catch (Exception e) { e.printStackTrace(); }finally { if (null != out){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); viewEvents(); } private void initViews() { btn_get_crop_from_album = (Button) findViewById(R.id.btn_get_crop_from_album); btn_get_crop_from_camera = (Button) findViewById(R.id.btn_get_crop_from_camera); btn_get_from_album = (Button) findViewById(R.id.btn_get_from_album); btn_get_from_camera = (Button) findViewById(R.id.btn_get_from_camera); btn_get_rel_from_camera = (Button) findViewById(R.id.btn_get_rel_from_camera); txt_img_path = (TextView) findViewById(R.id.txt_img_path); img = (ImageView) findViewById(R.id.img); } private void viewEvents() { btn_get_crop_from_album.setOnClickListener(this); btn_get_crop_from_camera.setOnClickListener(this); btn_get_from_album.setOnClickListener(this); btn_get_from_camera.setOnClickListener(this); btn_get_rel_from_camera.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_get_from_album:{ getImageFromAlbum(); break; } case R.id.btn_get_from_camera:{ getImageFromCamera(); break; } case R.id.btn_get_rel_from_camera:{ getRelImageFromCamera(); break; } case R.id.btn_get_crop_from_camera:{ getCropImageFromCamera(); break; } case R.id.btn_get_crop_from_album:{ getCropImageFromAlbum(); break; } } } public void getImageFromAlbum() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");//相片类型 startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); } public void getImageFromCamera() { String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)){ ima_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/"; Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent,REQUEST_CODE_CAPTURE_CAMERA); }else { Toast.makeText(getApplicationContext(),"请确认已插入SD卡",Toast.LENGTH_SHORT).show(); } } public void getRelImageFromCamera(){ String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)){ Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/rel_image"; File dir = new File(out_file_path); if (!dir.exists()){ dir.mkdirs(); } rel_ima_path = out_file_path + File.separator + System.currentTimeMillis() + ".jpg"; intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(rel_ima_path))); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, REQUEST_CODE_REL_CAPTURE_CAMERA); } } public void getCropImageFromCamera() { String out_img_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/crop_image"; File dir = new File(out_img_path); if (!dir.exists()){ dir.mkdirs(); } rel_ima_path = out_img_path + File.separator + System.currentTimeMillis() + ".jpg"; Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rel_ima_path))); startActivityForResult(intent,REQUEST_CODE_CROP_CAPTURE_CAMERA); } public void getCropImageFromAlbum() { String out_img_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/crop_chose"; File dir = new File(out_img_path); if (!dir.exists()){ dir.mkdirs(); } rel_ima_path = out_img_path + File.separator + System.currentTimeMillis() + ".jpg";// Intent intent = new Intent("android.intent.action.GET_CONTENT"); Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); intent.putExtra("crop", true);// intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rel_ima_path))); startActivityForResult(intent,REQUEST_CODE_REL_CAPTURE_CAMERA); }}
utils:
package com.example.xushuailong.mydopicture.utils;import android.annotation.TargetApi;import android.content.ContentUris;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Environment;import android.provider.DocumentsContract;import android.provider.MediaStore;@TargetApi(Build.VERSION_CODES.KITKAT)public class Utilty {/** * 在android4.4上获取资源的路径 * * @param context * @param uri * @return */public static String getPathFromKitKat(final Context context, final Uri uri) {final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {// ExternalStorageProviderif (isExternalStorageDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];if ("primary".equalsIgnoreCase(type)) {return Environment.getExternalStorageDirectory() + "/"+ split[1];}// TODO handle non-primary volumes}// DownloadsProviderelse if (isDownloadsDocument(uri)) {final String id = DocumentsContract.getDocumentId(uri);final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(id));return getDataColumn(context, contentUri, null, null);}// MediaProviderelse if (isMediaDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}final String selection = "_id=?";final String[] selectionArgs = new String[] { split[1] };return getDataColumn(context, contentUri, selection,selectionArgs);}}// MediaStore (and general)else if ("content".equalsIgnoreCase(uri.getScheme())) {// Return the remote addressif (isGooglePhotosUri(uri))return uri.getLastPathSegment();return getDataColumn(context, uri, null, null);}// Fileelse if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return null;}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 = context.getContentResolver().query(uri, projection,selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {final int index = cursor.getColumnIndexOrThrow(column);return cursor.getString(index);}} finally {if (cursor != null)cursor.close();}return null;}public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}public static boolean isGooglePhotosUri(Uri uri) {return "com.google.android.apps.photos.content".equals(uri.getAuthority());}}
activity_layout::
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.xushuailong.mydopicture.MainActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn_get_from_album" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get pic from album"/> <Button android:id="@+id/btn_get_crop_from_album" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get crop pic from album"/> <Button android:id="@+id/btn_get_from_camera" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get pic from camera"/> <Button android:id="@+id/btn_get_rel_from_camera" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get rel pic from camera"/> <Button android:id="@+id/btn_get_crop_from_camera" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get crop pic from camera"/> <TextView android:text="img_path: " android:maxLines="2" android:id="@+id/txt_img_path" android:layout_width="match_parent" android:layout_height="48dp" /> <ImageView android:src="@mipmap/ic_launcher" android:id="@+id/img" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitCenter"/> </LinearLayout></RelativeLayout>
这部分程序功能的bug是,当从相册选择的图片或拍照的图片太大的时候,ImageView就显示不出来图片,有待于进一步的优化。。。。
0 0
- 从相册或拍照获取图片,并实现图片的裁剪
- Android 拍照或从相册取图片并裁剪
- ImageView---拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- Android 拍照或从相册取图片并裁剪
- iOS从相机或相册获取图片并裁剪,再获取裁剪后的图片
- iOS 从相机或相册获取图片并裁剪
- iOS 从相机或相册获取图片并裁剪
- iOS 从相机或相册获取图片并裁剪
- Android 从相机或相册获取图片并裁剪
- 图片拍照或相册选择的实现以及裁剪功能
- Android实现类似QQ头像点击打开相册或者拍照,并获取裁剪后的图片
- Activity 设置切换动画
- java 合并文件
- perl use base 代替 @ISA
- request.getContextPath. getServletPath
- 收获地址的编写
- 从相册或拍照获取图片,并实现图片的裁剪
- 设置图片渐变
- 欢迎使用CSDN-markdown编辑器
- iOS CocoaPods1.0.0的一些基础知识
- lua 的坑
- iOS -- 读取plist表中数据到NSArray
- Js中Prototype、__proto__、Constructor、Object、Function关系介绍
- 如何用studio将一个Android工程转成一个jar文件
- OpenGl 4.x for Mac开发环境配置