介绍

在应用开发中,如果涉及到个人信息,头像一般是不可避免的,类似这种情况,我们就需要用到图片裁切的功能,实现头像裁切,然后上传给服务器。

一般裁切的做法就是图层叠加选取框,然后根据坐标,计算裁切区域,通过图形函数裁切,既然了解大概原理,造轮子的事情就不做了,上github找开源库,发现了一个叫做edmodo/cropper的库,是原生实现的裁切。

地址:https://github.com/edmodo/cropper

但是使用后发现这个库还存以下两个主要问题,体验就很不好了。

1、图片太大会出现无法显示

2、图片过小又无法自适应

难道就没有更好的办法了?

又百度了一下,发现原来android的Intent已经自带有裁切的action了,而且体验非常好,只需要在Intent附上参数就可以实现相册/相机裁切图片。

地址:https://github.com/ryanhoo/PhotoCropper

原理

1、请看参数

2、拍照裁切需要先将结果保存在本地,然后再读取保存的结果裁切,否则默认情况下拍照直接返回的结果是缩略图。

3、通过onActivityResult来处理结果。

实现

参考的项目是经过重构的,但我总觉得看的晕,所以demo就全部放在一个页面,加上了个人理解注释,方便学习。

CropParams类

package com.example.cropimage;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment; public class CropParams { public static final String CROP_TYPE = "image/*";
public static final String OUTPUT_FORMAT = Bitmap.CompressFormat.JPEG
.toString(); public static final int DEFAULT_ASPECT = 1;
public static final int DEFAULT_OUTPUT = 300; public Uri uri; public String type;
public String outputFormat;
public String crop; public boolean scale;
public boolean returnData;
public boolean noFaceDetection;
public boolean scaleUpIfNeeded; public int aspectX;
public int aspectY; public int outputX;
public int outputY; public CropParams() {
uri = Uri.fromFile(Environment.getExternalStorageDirectory())
.buildUpon().appendPath("crop_cache_file.jpg").build();
type = CROP_TYPE;
outputFormat = OUTPUT_FORMAT;
crop = "true";
scale = true;
returnData = false;
noFaceDetection = true;
scaleUpIfNeeded = true;
aspectX = DEFAULT_ASPECT;
aspectY = DEFAULT_ASPECT;
outputX = DEFAULT_OUTPUT;
outputY = DEFAULT_OUTPUT;
}
}

核心代码

package com.example.cropimage;

import java.io.File;
import java.io.FileNotFoundException; import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast; public class MainActivity extends ActionBarActivity {
ImageView imageView1;
CropParams mCropParams = new CropParams();
public static final int REQUEST_CROP = 127;
public static final int REQUEST_CAMERA = 128; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = (ImageView) findViewById(R.id.imageView1); // 弹出提示框选择照片
final String[] arrayFruit = new String[] { "拍照", "从相册选择照片" };
Dialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.ic_launcher)
.setItems(arrayFruit, new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// 进入相机
startActivityForResult(
buildCaptureIntent(mCropParams.uri),
REQUEST_CAMERA);
break;
case 1:
// 进入相册
startActivityForResult(
buildCropFromGalleryIntent(mCropParams),
REQUEST_CROP);
break;
default:
break;
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).create();
alertDialog.show();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Crop canceled!", Toast.LENGTH_LONG).show();
} else if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_CROP:
Log.d("cropImage", "Photo cropped!");
Toast.makeText(this, "Photo cropped!", Toast.LENGTH_LONG)
.show();
imageView1.setImageURI(mCropParams.uri);
break;
case REQUEST_CAMERA:
Intent intent = buildCropFromUriIntent(mCropParams);
startActivityForResult(intent, REQUEST_CROP);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} /**
* 结束后删除临时裁切图片,或者不删除,用来干别的。
*/
@Override
protected void onDestroy() {
File file = new File(mCropParams.uri.getPath());
if (file.exists()) {
boolean result = file.delete();
if (result)
Log.i("cropImage", "Cached crop file cleared.");
else
Log.e("cropImage", "Failed to clear cached crop file."); } else {
Log.w("cropImage",
"Trying to clear cached crop file but it does not exist.");
}
super.onDestroy();
} /**
* 创建裁切Intent
*
* @param action
* 操作
* @param params
* 参数
* @return
*/
public static Intent buildCropIntent(String action, CropParams params) {
return new Intent(action, null)
.setDataAndType(params.uri, params.type)
// .setType(params.type)
.putExtra("crop", params.crop).putExtra("scale", params.scale)
.putExtra("aspectX", params.aspectX)
.putExtra("aspectY", params.aspectY)
.putExtra("outputX", params.outputX)
.putExtra("outputY", params.outputY)
.putExtra("return-data", params.returnData)
.putExtra("outputFormat", params.outputFormat)
.putExtra("noFaceDetection", params.noFaceDetection)
.putExtra("scaleUpIfNeeded", params.scaleUpIfNeeded)
.putExtra(MediaStore.EXTRA_OUTPUT, params.uri);
} /**
* 这一步是在相机拍照完成之后调用,注意action。
*
* @param params
* @return
*/
public static Intent buildCropFromUriIntent(CropParams params) {
return buildCropIntent("com.android.camera.action.CROP", params);
} /**
* 创建相册裁切Intent
*
* @param params
* 奥秘全在params里
* @return
*/
public static Intent buildCropFromGalleryIntent(CropParams params) {
return buildCropIntent(Intent.ACTION_GET_CONTENT, params);
} /**
* 创建相机拍照Intent,由于相机拍照直接返回的是缩略图,所以一般的做法是拍照保存在本地之后,通过uri再读取一次
*
* @param uri
* 保存路径
* @return
*/
public static Intent buildCaptureIntent(Uri uri) {
return new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
MediaStore.EXTRA_OUTPUT, uri);
} /**
* 解析uri成bitmap
*
* @param context
* @param uri
* @return
*/
public static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
if (context == null || uri == null)
return null; Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}
}

完成之后看起来是这样的

   

demo地址:

链接:http://pan.baidu.com/s/1c0xqxEw 密码:u2ot

参考:

http://ryanhoo.github.io/blog/2014/05/26/the-ultimate-approach-to-crop-photos-on-android-1/

Android实现图片裁切的更多相关文章

  1. Android压缩图片到100K以下并保持不失真的高效方法

    前言:目前一般手机的相机都能达到800万像素,像我的Galaxy Nexus才500万像素,拍摄的照片也有1.5M左右.这么大的照片上传到服务器,不仅浪费流量,同时还浪费时间. 在开发Android企 ...

  2. 仿优酷Android客户端图片左右滑动(自动滑动)

    最终效果: 页面布局main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayou ...

  3. Javascript图片裁切

    最近浏览了不少网站的图片裁切效果,大部分的做法如下图所示(借用一张脚本之家的图片),通过改变裁切框的大小来选取合适的位置. 但本文介绍的是另外一种裁切方式,裁切框由开发者决定,图片大小由用户决定,通过 ...

  4. 用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片

    用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片 ticons的用法可以百度 这里记录下具体的编译方法 在安装了ticons和ImageMagickDisp ...

  5. Android 实现图片画画板

    本文主要讲述了Android 实现图片画画板 设计项目布局: <RelativeLayout xmlns:android="http://schemas.android.com/apk ...

  6. 关于Android中图片大小、内存占用与drawable文件夹关系的研究与分析

    原文:关于Android中图片大小.内存占用与drawable文件夹关系的研究与分析 相关: Android drawable微技巧,你所不知道的drawable的那些细节 经常会有朋友问我这个问题: ...

  7. android 拉伸图片

    Android拉伸图片用的是9.png格式的图片,这种图片可以指定图片的那一部分拉伸,那一部分显示内容,美工给的小图片也能有很好的显示效果. 原背景图片 可以看到原背景图片很小,即使在再长的文字,背景 ...

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

    转载声明:Ryan的博客文章欢迎您的转载,但在转载的同时,请注明文章的来源出处,不胜感激! :-)  http://my.oschina.net/ryanhoo/blog/86842 约几个月前,我正 ...

  9. 图片裁切插件jCrop的使用心得(三)

    在这一篇里,我来具体讲讲代码该如何写. 下面是jCrop的初始化代码 //图片裁剪插件Jcrop初始化 function initJcrop() { // 图片加载完成 document.getEle ...

随机推荐

  1. DB2 的create or update方法

    通过merge方法实现的: MERGE INTO IFEBASE.STYLE AS MT USING (SELECT :scenario AS SCENARIO_ID, :style AS SHAPE ...

  2. const int *p与int *const p的区别(转:csdn,suer0101)

    本文只是一篇学习笔记,是看了<彻底搞定C指针>中的相关篇幅后的一点总结,仅此而已! 一.先搞清const int *p与int const *p的区别 它们的区别就是:没有区别!! 无论谁 ...

  3. java多线程基础知识

    1.ThrTest.java 继承Thread类方式 public class ThrTest extends Thread { private String name; public ThrTest ...

  4. 由浅入深了解Thrift之结果封装

    一.thrift返回结果封装 Thrift文件添加版本号,方便对thrift的版本进行控制 服务与返回的数据类型分开定义 在项目中使用Thrift提供RPC服务时,很多情况下我们都会将返回的结果进行封 ...

  5. java 如何从配置文件(.properties)中读取内容

    1.如何创建.properties文件 很简单,建立一个txt文件,并把后缀改成.properties即可 2.将.properties文件拷入src的根目录下 3..properties文件内容格式 ...

  6. intelli IDEA node开发代码提示问题

    好几天没写代码了,今天新建一个项目,在引入rs这个文件系统模块时却没有关于这个模块的代码提示,着实令人恶心啊.还好最终解决了. 在没有代码提示的时候点击如下图标: 出现如下的界面,其中有个Edit u ...

  7. Tomcat目录结构

    首先来了解一下Tomcat5.5的目录结构: /bin:存放windows或Linux平台上启动和关闭Tomcat的脚本文件 /conf:存放Tomcat服务器的各种全局配置文件,其中包括server ...

  8. lintcode:交换链表当中两个节点

    题目 给你一个链表以及两个权值v1和v2,交换链表中权值为v1和v2的这两个节点.保证链表中节点权值各不相同,如果没有找到对应节点,那么什么也不用做. 注意事项 你需要交换两个节点而不是改变节点的权值 ...

  9. <iostream> 和 <iostream.h>的区别 及 Linux下编译iostream.h的方法

    0.序言 其实2者主要的区别就是iostream是C++标准的输入输出流头文件,而iostream.h是非标准的头文件. 标准头文件iostream中的函数属于标准命令空间,而iostream.h中的 ...

  10. Bootstrap全屏

    1.由于bootstrap中的.containter是根据媒体查询定死了width,所以页面不会占满全屏,若要全屏,则最外面的div的class不能用container(或改用.container-f ...