How to crop large photos with Android MediaStore

Android开发经典案例:实现图片裁剪功能 本文介绍了如何在Android中实现图片裁剪功能,并提供了相应的源代码。通过这些代码,您可以轻松地在自己的Android应用中实现图片裁剪功能,满足不同场景的需求。通过上述代码,我们可以选择一张图片进行裁剪,并将裁剪后的图片显示在ImageView中。在Android开发中,图片处理是一个常见的需求。本文将介绍如何使用Android提供的相关API实现图片裁剪,并提供相应的源代码。在对应的Activity中,我们通过选取一张图片并显示在ImageView中。的隐式调用,并设置了相应的裁剪参数。 阅读详情

Overview

I’m writing this article to publish my brief research on the MediaStore crop functionality.  Basically, if you want to write an application that leverages the existing Media Gallery and allows a user to pick (with optional face recognition) a portion of his/her image for use inside your application.  There is an intent to do this, some bugs associated with it, and an overall lack of documentation on how to do it.  Also, this article is based on 2.1 and tested on a Nexus One.  The implementation of the Nexus One appears to be written by these guys (according to their site), see Media Gallery for Nexus One.

Feedback

This article is based on my research, needed for an application I wrote.  If you find improvements over my suggested implementation, please let me know.  I’ll update this post accordingly.

Intent Details:

First, lets discuss this Intent, and its features.    After seeing some example code, I found that I could call it easily using an Intent like this:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType(“image/*”);
intent.putExtra(“crop”, “true”);
…

However, this is when I lacked additional documentation, what are the options, etc…  So, I have put together a table, and a demo program, in an attempt to demonstrated all available options from this control.  You may use my example code in your application, and expand upon it.  I’ll attach it to this post.

Exta Options Table for image/* crop:

 

SetExtraDataTypeDescription
cropStringSignals the crop feature
aspectXintAspect Ratio
aspectYintAspect Ratio
outputXintwidth of output created from this Intent
outputYintwidth of output created from this Intent
scalebooleanshould it scale
return-databooleanReturn the bitmap with Action=inline-data by using the data
dataParcelableBitmap to process, you may provide it a bitmap (not tested)
circleCropStringif this string is not null, it will provide some circular cr
MediaStore.EXTRA_OUTPUT ("output")URISet this URi to a File:///, see example code

Now, the biggest confusion is going to be around this MediaStore.EXTRA_OUTPUT and return-data options.

You basically have 2 ways to get the bitmap back from this Intent, you can ask for it inline or provide a Uri that it can write to.

Option #1:  If you set return-data to "true", you will get back an Action = inline-data, and the bitmap returned will be inside the (Bitmap)extras.getParcelable("data").  Note:  If the image ends up being to large, you will get a nasty exception with this method, so you are restricted to keeping your outputX and outputY small.  In my code example attached, I did NOT use that method because of this reason.

Here is the code from CropImage.java (Android source code) where they write it inline:


// Return the cropped image directly or save it to the specified URI.
Bundle myExtras = getIntent().getExtras();
if (myExtras != null && (myExtras.getParcelable("data") != null
|| myExtras.getBoolean("return-data")))
{
Bundle extras = new Bundle();
extras.putParcelable("data", croppedImage);
setResult(RESULT_OK,(new Intent()).setAction("inline-data").putExtras(extras));
finish();

Option #2:  If you set return-data to "false", you will not receive a Bitmap back from the onActivityResult Intent in-line, instead you will need to set MediaStore.EXTRA_OUTPUT to a Uri (of File scheme only) where you want the Bitmap to be stored.  This has some restrictions, first you need to have a temp filesystem location in order to give the file scheme URI, not a huge problem (except on some devices that don't have sdcards).

Here is the code from CropImage.java (Android source code) where they write it to your Uri:


if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
if (outputStream != null) {
croppedImage.compress(mOutputFormat, 75, outputStream);
}
} catch (IOException ex) {
// TODO: report error to caller
Log.e(TAG, "Cannot open file: " + mSaveUri, ex);
} finally {
Util.closeSilently(outputStream);
}
Bundle extras = new Bundle();
setResult(RESULT_OK, new Intent(mSaveUri.toString())
.putExtras(extras));
}

Example Code

I have attached some example code that should allow you to test various configurations.  Let me know if you find it useful (or not).D
Download here -> MediaStoreTest

From the code (the essential parts)


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiz = this;
setContentView(R.layout.main);
mBtn = (Button) findViewById(R.id.btnLaunch);
photo = (ImageView) findViewById(R.id.imgPhoto);

 

mBtn.setOnClickListener(new OnClickListener(){

public void onClick(View v) {
try {
// Launch picker to choose photo for selected contact
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("scale", scale);
intent.putExtra("return-data", return_data);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection",!faceDetection); // lol, negative boolean noFaceDetection
if (circleCrop) {
intent.putExtra("circleCrop", true);
}

startActivityForResult(intent, PHOTO_PICKED);
} catch (ActivityNotFoundException e) {
Toast.makeText(thiz, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
}
}
});

}

private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}

private File getTempFile() {
if (isSDCARDMounted()) {

File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(thiz, R.string.fileIOIssue, Toast.LENGTH_LONG).show();
}
return f;
} else {
return null;
}
}

private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();

if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {
case PHOTO_PICKED:
if (resultCode == RESULT_OK) {
if (data == null) {
Log.w(TAG, "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, R.string.no_photo_picked,
Toast.LENGTH_SHORT);
t.show();
return;
}

final Bundle extras = data.getExtras();
if (extras != null) {
File tempFile = getTempFile();
// new logic to get the photo from a URI
if (data.getAction() != null) {
processPhotoUpdate(tempFile);
}
}
}
break;
}
}

Android自定义 view之图片裁剪从设计到实现 图片裁剪从设计到实现 阅读详情

相关推荐

Windows版本Carla(含RoadRunner插件)源码安装+RoadRunner地图导入

通过跳转浏览器账号密码登录github,不要选择Fine-grained personal access tokens,在git clone时会显示非授权,也不要使用Windows凭据!核心指令:编译PythonAPI–make PythonAPI,,编译Server–make launch,封装”游戏“–make package。完成安装后,在已安装->2022版本右侧->更多->导入配置,选择配置文件(需将配置文件内容更新为手册内容,如下图)->详细信息,更新。不要修改版本,执行上面指令即可!

winnizap的博客 1467

Glide4用法全解析

添加依赖权限对于 Glide 加载 URL 并不是必需的,但是它将帮助 Glide 处理 片状网络(flaky network) 和飞行模式。如果你正在从 URL 加载图片,Glide 可以自动帮助你处理片状网络连接:它可以监听用户的连接状态并在用户重新连接到网络时重启之前失败的请求。如果 Glide 检测到你的应用拥有 ACCESS_NETWORK_STATE 权限,Glide 将自动监听连接状态而不需要额外的改动如果要使用来将 Glide 的缓存存储到公有 SD 卡上,就需要添加权限。混淆。

新一代螺丝工的博客 1304

排查单片机不工作的‘玄学’故障:从LDO选型、复位电路到焊接不良的完整避坑指南

本文深入剖析单片机不工作的常见硬件故障,从LDO选型、复位电路设计到PCB布局和焊接工艺,提供系统性排查方法。重点分析3.3V电源稳定性、LDO动态响应特性及复位电路设计要点,帮助工程师快速定位和解决嵌入式系统中的'玄学'故障,提升产品可靠性。

weixin_30655569的博客 387

Android裁剪图片总结

在网上搜索了Android裁剪图片的方式,发现有两种: 1、裁剪后返回的不是Intent中指定尺寸的图,而是缩略图 2、裁剪后返回的是指定大小的图片 关于这两种裁剪方式,我把自己试验后的结果记录如下: 1、裁剪成缩略图模式,步骤如下: (1)先通过Intent选择图片,获取图片URI,代码如下: Intent intent = new Intent(Intent.ACTION_PICK

记录技术,记录生活 5274

神经网络基础-从零开始搭建一个神经网络

人工神经网络(Articial Neural Network,简写为ANN)也称为神经网络(NN),是一种模仿生物神经网络和功能的计算模型,人脑可以看做是一个生物神经网络,由众多的神经元连接而成,各个神经元传递复杂的电信号,树突接收到输入信号,然后对信号进行处理,通过轴突输出信号。人工神经网络也是类似,通过模仿人脑的“学习机器”,通过不断“看”数据(比如图片,数字),自己总结规律,最终学会预测(比如分类图片)在深度学习中,损失函数是用来衡量模型参数的质量的函数,衡量的方式是比较网络输出和真实输出的差异。

Zach的博客 4014

CA51F3系列(国产)+低功耗模式

CA51F351P6芯片是基于1T 8051内核的8位微控制器,通常情况下,运行速度比传统的8051芯片快10倍,性能更加优越。内置8K Flash程序存储器,可多次重复编程的特性给用户开发带来了极大的方便。不仅保留了传统8051芯片的基本特性,还集成了12Bit ADC、LCD/LED驱动、Touch Key、16Bit PWM、 UART、RTC、低电压检测(LVD)等功能模块。支持IDLE、STOP和低速运行三种省电模式以适应不同功耗要求的应用。

WANGJIHUIwang的博客 572

Android自定义View实现图片裁剪功能(本地选择图片进行裁剪)

Android 自定义View裁剪工具

qq_41008818的博客 4275

Ubuntu20.04系统Cuckoo sandbox所需环境搭建及安装(超详细图文)

请勿叫我大神,我只是互联网的搬运工~ 前言 本教程以Ubuntu20桌面版作为示范,服务器版同样适用,但可能稍微麻烦一点,服务器版本的话安装Xmanage套装使用可能会相对轻松一些,由于后面会使用到vbox的使用,对vbox命令行操作不熟悉的小伙伴用xmanage可能会相对轻松一点。 提示:以下是本篇文章正文内容,下面案例可供参考 安装ubuntu20桌面版 步骤1:转到https://ubuntu.com/download/desktop下载下载.iso。 步骤2:使用您选择的虚拟机监控程序(VMWa

ElsonHY的博客 1万+

Android中图片的裁剪与压缩

1)matrix不缩放,图片与控件左上角对齐,当图片大小超过控件时将被裁剪(2)center不缩放,图片与控件中心点对齐,当图片大小超过控件时将被裁剪以完整显示图片为目标,不剪裁,当显示不下的时候将缩放,能够显示的情况下不缩放以填满整个控件为目标,等比缩放,超过控件时将被裁剪(宽高都要填满,所以只要图片宽高比与控件宽高比不同时,一定会被剪裁)(5)fitCenter(默认)...

java521666的博客 3645

新手必看:5分钟搞定Unitree Go1机器狗Gazebo仿真运动控制(附按键图解)

本文为新手提供了Unitree Go1机器狗在Gazebo仿真环境中实现运动控制的快速指南。通过5分钟极简配置和按键图解,帮助开发者快速掌握宇树科技明星产品的基础操作,包括环境搭建、仿真启动和运动控制技巧,适合零基础用户快速上手。

weixin_42550597的博客 300

HSM 网络安全 信息安全

HSM HSM信息安全功能 汽车电子网络安全中HSM 的应用场景 选择适合汽车电子网络安全的 HSM 符合汽车安全标准和法规要求的HSM HSM 在汽车电子网络安全中的可靠性和安全性 评估汽车电子网络的安全性 汽车 HSM(Hardware Security Module)模块开发 汽车 HSM(Hardware Security Module)模块测试

天赐好车的博客 1237

Android 拍照、从相册获取及裁剪的相关实现

转载地址:http://www.cnblogs.com/wytings/p/5260334.html 首先这些功能都是通过Intent去启动系统的服务去实现的,所以自然就有相应的Action。相关Actiong如下:   拍照——MediaStore.ACTION_IMAGE_CAPTURE ("android.media.action.IMAGE_CAPTURE")

相公 1150

华为OD面试八股真题 - 操作系统相关 - 2

华为OD技术面,操作系统相关八股真题提供详细解答,这篇博客主要涉及于进程和线程相关知识点

qq_45776114的博客 967

Glide4.0 centerCrop属性和圆角 冲突

最近有个工作中有个需求就是展示的图片必须圆角、正方形,当时一想这太尼玛简单了,无非就是设置一个图片参数的大小,然后在设置一个centerCrop的属性,在自定义一个类去继承BitmapTransformation重画一下。 结果写的时候发现,在glide4.0上面 centerCrop和圆角图片有冲突只能显示一个,结果就度娘问了一边,大部分都是下面这行代码,发现这个在glide4.0上面

flyinbed_的博客 1万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Android大图片裁剪终极解决方案

转自:http://blog.youkuaiyun.com/floodingfire/article/details/8144604 首先,让我们探讨下Intent以及它的特点。在看了一些代码示例以后,我发现我可以很轻松的使用如下的Intent调用裁剪功能:  1 Intent intent = new Intent(Intent.ACTION_GET_CONTE

qie7892683的专栏 3741

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Android中 调用图库 选择 图片的参数理解

网上有不少文章说怎么调用图库去选择并裁剪图片,却对这些参数说的比较少。 今天把看懂的一些参数总结一下: Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);    intent.setType("image/*");    //这个参数是确定要选择的内容为图片 intent.putExtra("crop", "cir

4797

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Android调用系统相机/相册并裁剪详解

效果展示 关键技术 android文件管理系统 代码编写 第一步:布局文件的准备 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://...

我想月薪过万的博客 2729

android系统的裁剪图片,android系统图片裁剪

How to crop large photos with Android MediaStoreOverviewI’m writing this article to publish my brief research on the MediaStore crop functionality. Basically, if you want to write an application that...

weixin_39546520的博客 131

转载——Android大图片裁剪终极解决方案

约几个月前,我正为公司的APP在Android手机上实现拍照截图而烦恼不已。 上网搜索,确实有不少的例子,大多都是抄来抄去,而且水平多半处于demo的样子,可以用来讲解知识点,但是一碰到实际项目,就漏洞百出。 当时我用大众化的解决方案,暂时性的做了一个拍照截图的功能,似乎看起来很不错。问题随之而来,我用的是小米手机,在别的手机上都运行正常,小米这里却总是碰钉子。虽然我是个理性的米粉,但

5586

解决安卓7.0系统裁剪图片出错问题

Android7.0中为了提高私有文件的安全性,对file:// Uri 类型的Uri做出了限制,导致一些APP的功能无法正常使用。前几天的一个头像裁剪问题被提上了日程,开始只是修改了拍照的Uri,忘记了还要裁剪大笑,因为直接使用的系统裁剪导致裁剪出了问题。下面贴出解决安卓7.0裁剪出问题的解决方案。首先拍照的解决在我以前的博客也有涉及,顺便打打广告:

波波的博客 6782

Android大图片裁剪终极解决方案(上:原理分析)

转载声明:Ryan的博客文章欢迎您的转载,但在转载的同时,请注明文章的来源出处,不胜感激! :-) http://my.oschina.net/ryanhoo/blog/86842 约几个月前,我正为公司的APP在Android手机上实现拍照截图而烦恼不已。 ...

cibaoqb025084的博客 370

Android借助系统自带图片裁剪集成图片选择以及7.0适配

一、前文  之前使用的图片裁剪功能一直是使用第三方的,也没时间去思考自己写一个的想法。后来无意间发现android自己本来就有裁剪功能,所以自己动手去集成了一把,并且把自己的权限封装以及7.0的适配都加进去二、注意的几个点  其实也没有什么好说的,基本没有难度,只是有几个需要注意的点 1.一个是7.0的文件安全机制,7.0之后android对于文件的安全增加了保护,在部分地方使用Uri会产生Fil

qq_24859309的博客 1612

Android 图片裁剪 (附源码)

Android 图片裁剪前言正文一、创建并配置项目二、权限申请三、获取图片Uri四、图片裁剪尾声 运行效果图 前言   图片裁剪是对图片进行区域选定,然后裁剪选定的区域,形成一个图片,然后再对这个图片进行压缩,最终返回结果图片。 正文   从上面的描述来看貌似是挺简单的是吧,不过实际操作起来就没有那么简单了,下面先来看看简单的实现方式,就是Android自带的裁剪。 一、创建并配置项目 我们依然从创建项目开始讲起,这虽然有一些繁琐,但无疑可以让每一个Android开发者看懂。创建一个名为PictureCr

晨曦 9466

通过Bundle传递不同Intent之间的原始数据

 <br />一个Activity需要调用另外一个Activity的同时传递数据,可以利用android.os.Bundle对象封装数据的能力,将欲传递的数据或参数,通过Bundle来传递不同Intent之间的数据。<br /><br />Activity1:<br /><br />public class Activity1 extends Activity   {       @Override   public void onCreate(Bundle savedInstanceState)     

happy_6678的专栏 1977
上一篇: 在Android模拟器中删除APK的方法
下一篇: 如何使Android应用程序获取系统权限【转】
dotphoenix
博客等级 码龄19年 208粉丝 137原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值