Android大图片裁剪 拍照 截图

本文介绍如何在Android应用中实现拍照截图功能,并通过Uri进行图片的大图与小图操作。此外,还提供了如何调用系统裁剪工具来处理图片的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载声明:Ryan的博客文章欢迎您的转载,但在转载的同时,请注明文章的来源出处,不胜感激! :-) 

http://blog.youkuaiyun.com/floodingfire/article/details/8144617


    上一篇博客中,我们学习到了如何使用Android相册截图。在这篇博客中,我将向大家展示如何拍照截图。

    拍照截图有点儿特殊,要知道,现在的Android智能手机的摄像头都是几百万的像素,拍出来的图片都是非常大的。因此,我们不能像对待相册截图一样使用Bitmap小图,无论大图小图都统一使用Uri进行操作。

    一、首先准备好需要使用到的Uri:

1 private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
2 Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap

    二、使用MediaStore.ACTION_IMAGE_CAPTURE可以轻松调用Camera程序进行拍照:

1 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
2 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
3 startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE
    三、接下来就可以在  onActivityResult中拿到返回的数据(Uri),并将Uri传递给截图的程序。
01 switch (requestCode) {
02 case TAKE_BIG_PICTURE:
03     Log.d(TAG, "TAKE_BIG_PICTURE: data = " + data);//it seems to be null
04     //TODO sent to crop
05     cropImageUri(imageUri, 800400, CROP_BIG_PICTURE);
06      
07     break;
08 case TAKE_SMALL_PICTURE:
09     Log.i(TAG, "TAKE_SMALL_PICTURE: data = " + data);
10     //TODO sent to crop
11     cropImageUri(imageUri, 300150, CROP_SMALL_PICTURE);
12      
13     break;
14 default:
15     break;
16 }
    可以看到,无论是拍大图片还是小图片,都是使用的Uri,只是尺寸不同而已。我们将这个操作封装在一个方法里面。
01 private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){
02     Intent intent = new Intent("com.android.camera.action.CROP");
03     intent.setDataAndType(uri, "image/*");
04     intent.putExtra("crop""true");
05     intent.putExtra("aspectX"2);
06     intent.putExtra("aspectY"1);
07     intent.putExtra("outputX", outputX);
08     intent.putExtra("outputY", outputY);
09     intent.putExtra("scale"true);
10     intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
11     intent.putExtra("return-data"false);
12     intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
13     intent.putExtra("noFaceDetection"true); // no face detection
14     startActivityForResult(intent, requestCode);
15 }
    四、最后一步,我们已经将数据传入裁剪图片程序,接下来要做的就是处理返回的数据了:
01 switch (requestCode) {
02 case CROP_BIG_PICTURE://from crop_big_picture
03     Log.d(TAG, "CROP_BIG_PICTURE: data = " + data);//it seems to be null
04     if(imageUri != null){
05         Bitmap bitmap = decodeUriAsBitmap(imageUri);
06         imageView.setImageBitmap(bitmap);
07     }
08     break;
09 case CROP_SMALL_PICTURE:
10     if(imageUri != null){
11         Bitmap bitmap = decodeUriAsBitmap(imageUri);
12         imageView.setImageBitmap(bitmap);
13     }else{
14         Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data);
15     }
16     break;
17 default:
18     break;
19 }

效果图:


代码托管于GitHub,会不定期更新:https://github.com/ryanhoo/PhotoCropper

 

http://mzh3344258.blog.51cto.com/1823534/808837



public class MyInformationActivity extends Activity  {

	private PopupWindow mImageSetWindow;

	private View mPopView;
 
	private LProgressDialog mDialog;

	private String IMAGE_FILE_LOCATION = "file:///";// temp file
	private String IMAGE_FILE_NAME = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
 
		setContentView(R.layout.me_page_information);
 
	}
 

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (mImageSetWindow != null) {
			mImageSetWindow.dismiss();
		}
		switch (requestCode) {
 
		case 1: // 拍照
			if (resultCode == Activity.RESULT_OK) {
				startPhotoZoom(Uri.parse(IMAGE_FILE_LOCATION + IMAGE_FILE_NAME));
			}
			break;
		case 2: // 相册
			if (data == null)
				break;
			Uri originalUri = data.getData();
			String path = originalUri.toString();
			String[] projection = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(originalUri, projection, null, null,
					null);
			if (cursor != null) {
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 最后根据索引值获取图片路径
				path = cursor.getString(column_index);
				try {
					if (Integer.parseInt(Build.VERSION.SDK) < 14) {
						cursor.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
                        //在4.4之后读取图片的地址发生改变,所以加了后面的代码。
                         <pre name="code" class="java">if (TextUtils.isEmpty(path)){ 
	                    if (oldPath!=null && oldPath.contains("/image%3A")) {
	                		String id = oldPath.split("/image%3A")[1];
	                    	//定义索引字段
	                    	String[] column = { MediaStore.Images.Media.DATA };
	                    	String sel = MediaStore.Images.Media._ID + "=?";
	                    	Cursor cursor2 = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
	                    	column, sel, new String[]{ id }, null);
	                    	int columnIndex = cursor2.getColumnIndex(column[0]);
	                    	if (cursor2.moveToFirst()) {
	                    	//DATA字段就是本地资源的全路径
	                    		path = cursor2.getString(columnIndex);
	                    	}
	                    	//关闭游标
	                    	cursor2.close();
						}
	                    if (TextUtils.isEmpty(path)){ 
	                    	return;
	                    }
                    }

                  Logger.getLogger().e("======path====>" + path);File temp = new File(path);startPhotoZoom(Uri.fromFile(temp));break;case 3:if (data != null) {savePicData(data);}break;}}String photoPath = "";/** * 保存裁剪之后的图片数据到SDCARD中 * * @param picdata */private void savePicData(Intent picdata) {try {Bundle extras = picdata.getExtras();if (extras != null) {Bitmap photo = extras.getParcelable("data");String photoName = GameApp.getInstance().getmApp_init_token();String fileName = RemoteImageView.getDirectory("")+"/"+photoName+".png";File file = new File(fileName);if(file.exists()){file.delete();}file.createNewFile(); OutputStream outStream = new FileOutputStream(file); photo.compress(Bitmap.CompressFormat.JPEG, 80, outStream); outStream.flush(); outStream.close(); //上传修改的头像 // upLoadImage(photo);}} catch (Exception e) {e.printStackTrace();}}/** * 裁剪图片方法实现 * * @param uri */public void startPhotoZoom(Uri uri) {Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");intent.putExtra("crop", "true");intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);intent.putExtra("outputX", 90);intent.putExtra("outputY", 90);intent.putExtra("return-data", true);startActivityForResult(intent, 3);}private void popSelectWindow(View parent) {DisplayMetrics displayMetrics = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);int height = displayMetrics.heightPixels;int width = displayMetrics.widthPixels;if (mImageSetWindow == null) {LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);mPopView = layoutInflater.inflate(R.layout.popwindow_set_picture,null);Button cameraButton = (Button) mPopView.findViewById(R.id.captureButton);Button selectImageButton = (Button) mPopView.findViewById(R.id.selectImageButton);Button cancelButton = (Button) mPopView.findViewById(R.id.cancelButton);cameraButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);IMAGE_FILE_NAME = System.currentTimeMillis() + ".png";intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.parse(IMAGE_FILE_LOCATION + IMAGE_FILE_NAME));startActivityForResult(intent, 1);}});selectImageButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");startActivityForResult(intent, 2);}});cancelButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {mImageSetWindow.dismiss();}});mImageSetWindow = new PopupWindow(mPopView, width, height / 2);}// 使其聚集mImageSetWindow.setFocusable(true);// 设置允许在外点击消失mImageSetWindow.setOutsideTouchable(true);// 这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景mImageSetWindow.setBackgroundDrawable(new BitmapDrawable());// popupWindow.showAsDropDown(parent, 20, 30);mImageSetWindow.showAtLocation(parent, Gravity.LEFT | Gravity.BOTTOM,0, 0);}private Handler mUiHandler = new Handler() {public void handleMessage(Message msg) {super.handleMessage(msg); if (msg.obj != null) {String strInfo = msg.obj.toString();ToastUtils.showTextToast(MyInformationActivity.this, strInfo);return;}if (msg.what == MESSAGE_UPLOAD_FAILURE) {ToastUtils.showTextToast(MyInformationActivity.this, "上传失败");}if (msg.what == MESSAGE_UPLOAD_SUCCESS) {ToastUtils.showTextToast(MyInformationActivity.this, "上传成功"); }}};public static final int MESSAGE_UPLOAD_FAILURE = 10;public static final int MESSAGE_UPLOAD_SUCCESS = 20; }
 


基于Spring Boot搭建的一个多功能在线学习系统的实现细节。系统分为管理员和用户两个主要模块。管理员负责视频、文件和文章资料的管理以及系统运营维护;用户则可以进行视频播放、资料下载、参与学习论坛并享受个性化学习服务。文中重点探讨了文件下载的安全性和性能优化(如使用Resource对象避免内存溢出),积分排行榜的高效实现(采用Redis Sorted Set结构),敏感词过滤机制(利用DFA算法构建内存过滤树)以及视频播放的浏览器兼容性解决方案(通过FFmpeg调整MOOV原子位置)。此外,还提到了权限管理方面自定义动态加载器的应用,提高了系统的灵活性和易用性。 适合人群:对Spring Boot有一定了解,希望深入理解其实际应用的技术人员,尤其是从事在线教育平台开发的相关从业者。 使用场景及目标:适用于需要快速搭建稳定高效的在线学习平台的企业或团队。目标在于提供一套完整的解决方案,涵盖从资源管理到用户体验优化等多个方面,帮助开发者更好地理解和掌握Spring Boot框架的实际运用技巧。 其他说明:文中不仅提供了具体的代码示例和技术思路,还分享了许多实践经验教训,对于提高项目质量有着重要的指导意义。同时强调了安全性、性能优化等方面的重要性,确保系统能够应对规模用户的并发访问需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值