效果例如以下:

看代码:

MainActivity类中:

package com.example.ceshidemo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class MainActivity extends Activity {
private static final int PHOTO_REQUEST_CAREMA = 1;
private static final int PHOTO_REQUEST_GALLERY = 2;
private static final int PHOTO_REQUEST_CUT = 3;
private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
private File tempFile;
private CircleImageView headIcon; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView() { headIcon = (CircleImageView) findViewById(R.id.headIcon);
headIcon.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
changeHeadIcon();
}
});
changeTheme();
File file = new File(MainActivity.this.getFilesDir(), "_head_icon.jpg");
if (file.exists()) {
headIcon.setImageURI(Uri.fromFile(file));
}
}
private void changeTheme() {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.HOUR_OF_DAY));
if (c.get(Calendar.HOUR_OF_DAY) < 18 && c.get(Calendar.HOUR_OF_DAY) >= 6) {
headIcon.setImageResource(R.drawable.ic_hehe);
} else {
headIcon.setImageResource(R.drawable.ic_launcher);
}
}
private void changeHeadIcon() {
final CharSequence[] items = { "相冊", "拍照" };
AlertDialog dlg = new AlertDialog.Builder(MainActivity.this)
.setTitle("选择图片")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// 这里item是依据选择的方式。
if (item == 0) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,
PHOTO_REQUEST_GALLERY);
} else {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
tempFile = new File(Environment
.getExternalStorageDirectory(),
PHOTO_FILE_NAME);
Uri uri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent,
PHOTO_REQUEST_CAREMA);
} else {
Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!",
Toast.LENGTH_SHORT).show();
}
}
}
}).create();
dlg.show();
} @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_REQUEST_GALLERY) {
if (data != null) {
Uri uri = data.getData();
Log.e("图片路径??", data.getData() + "");
crop(uri);
} } else if (requestCode == PHOTO_REQUEST_CAREMA) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
crop(Uri.fromFile(tempFile));
} else {
Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片! ",
Toast.LENGTH_SHORT).show();
} } else if (requestCode == PHOTO_REQUEST_CUT) {
if (data != null) {
final Bitmap bitmap = data.getParcelableExtra("data");
headIcon.setImageBitmap(bitmap);
// 保存图片到internal storage
FileOutputStream outputStream;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
// out.close();
// final byte[] buffer = out.toByteArray();
// outputStream.write(buffer);
outputStream = MainActivity.this.openFileOutput("_head_icon.jpg",
Context.MODE_PRIVATE);
out.writeTo(outputStream);
out.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
if (tempFile != null && tempFile.exists())
tempFile.delete();
} catch (Exception e) {
e.printStackTrace();
} }
} private void crop(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", 250);
intent.putExtra("outputY", 250);
intent.putExtra("outputFormat", "JPEG");
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
}

在这里自定了一个圆形的View:CircleImageView

package com.example.ceshidemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; public class CircleImageView extends ImageView{ private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP; private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 1; private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK; private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF(); private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint(); private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH; private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight; private float mDrawableRadius;
private float mBorderRadius; private boolean mReady;
private boolean mSetupPending; public CircleImageView(Context context) {
super(context); init();
} public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
} public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR); a.recycle(); init();
} private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true; if (mSetupPending) {
setup();
mSetupPending = false;
}
} @Override
public ScaleType getScaleType() {
return SCALE_TYPE;
} @Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
} @Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
} canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
} @Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
} public int getBorderColor() {
return mBorderColor;
} public void setBorderColor(int borderColor) {
if (borderColor == mBorderColor) {
return;
} mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
} public int getBorderWidth() {
return mBorderWidth;
} public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
} mBorderWidth = borderWidth;
setup();
} @Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
} @Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
} @Override
public void setImageResource(int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
} @Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
} private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
} if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} try {
Bitmap bitmap; if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
} Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
} private void setup() {
if (!mReady) {
mSetupPending = true;
return;
} if (mBitmap == null) {
return;
} mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth); mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2); mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2); updateShaderMatrix();
invalidate();
} private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0; mShaderMatrix.set(null); if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
} mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth); mBitmapShader.setLocalMatrix(mShaderMatrix);
} }

main_activity.xml文件:

<?

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:circleimageView="http://schemas.android.com/apk/res/com.example.ceshidemo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:id="@+id/bt_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照或者选择图片" >
</TextView> <com.example.ceshidemo.CircleImageView
android:id="@+id/headIcon"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
circleimageView:border_color="#ffffff"
circleimageView:border_width="1dp" /> </LinearLayout>

自己定义圆形的属性文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DonutProgress">
<attr name="donut_progress" format="integer"/>
<attr name="donut_max" format="integer"/> <attr name="donut_unfinished_color" format="color"/>
<attr name="donut_finished_color" format="color"/> <attr name="donut_finished_stroke_width" format="dimension"/>
<attr name="donut_unfinished_stroke_width" format="dimension"/> <attr name="donut_text_size" format="dimension"/>
<attr name="donut_text_color" format="color"/> <attr name="donut_prefix_text" format="string"/>
<attr name="donut_suffix_text" format="string"/> <attr name="donut_background_color" format="color"/>
</declare-styleable>
<declare-styleable name="CircleImageView">
<attr name="border_width" format="dimension" />
<attr name="border_color" format="color" />
</declare-styleable>
</resources>

上面全部代码,点击demo下载測试 :http://download.csdn.net/detail/onceing/8884045

Android设置拍照或者上传本地图片的更多相关文章

  1. tinymce4.x 上传本地图片(自己写个插件)

    tinymce是一款挺不错的html文本编辑器.但是添加图片是直接添加链接,不能直接选择本地图片. 下面我写了一个插件用于直接上传本地图片. 在tinymce的plugins目录下新建一个upload ...

  2. tinymce4.x 上传本地图片 (转载)

    转载自:http://www.cnblogs.com/fhen/p/5809514.html tinymce4.x 上传本地图片   tinymce是一款挺不错的html文本编辑器.但是添加图片是直接 ...

  3. KindEditor上传本地图片在ASP.NET MVC的配置

    http://www.cnblogs.com/upupto/archive/2010/08/24/1807202.html 本文解决KindEditor上传本地图片在ASP.NET MVC中的配置. ...

  4. .net mvc4 利用 kindeditor 上传本地图片

    http://blog.csdn.net/ycwol/article/details/41824371?utm_source=tuicool&utm_medium=referral 最近在用k ...

  5. 个人永久性免费-Excel催化剂功能第102波-批量上传本地图片至网络图床(外网可访问)

    自我突破,在100+功能后,再做有质量的功能,非常不易,相对录制视频这些轻松活,还是按捺不住去写代码,此功能虽小,但功课也做了不少,希望对真正有需要的群体带来一些惊喜. 背景介绍 图床的使用,一般是写 ...

  6. html5上传本地图片,在线预览及裁剪(filereader,canvas)

    1 我们常常需要上传头像,点击上传按钮时候需要预览一下,使用filereader方法无需和后台交互,代码如下: //本地图片在上传之前的预览效果 //图片上传预览 function previewIm ...

  7. 有道云笔记Markdown上传本地图片的方法

    有道云笔记截图&保存   方法有多种,例如:开通有道云笔记VIP会员.先将图片文件上传到有道云笔记后使用图片的分享链接.说到底还是使用的 Markdown 的图片功能 ![图片名称](图片链接 ...

  8. js上传本地图片遇到的问题

    1.改变页面文件上传默认的样式 <input type="text" size="20" id="upfile" style=&quo ...

  9. kindeditor上传本地图片实例

    所需插件:kindeditor下载   密码: 5ry4 jsp文件: <script type="text/javascript" language="javas ...

随机推荐

  1. C3P0连接池一些基本配置

    C3P0连接池配置 数据库连接是一个耗费大量资源且相当慢的操作,所以为了提高性能和连接速度,诞生了连接池这样的概念. 在多用户并发操作过程中,连接池尤为重要. 它是将那些已连接的数据库连接存放在一个容 ...

  2. Asp.net中的一个判断session是否合法的做法

    1 if (Session["UserID"] == "" || Session["UserID"] == null) 2 { 3     ...

  3. POJ 2438 Children's Dining(哈密顿回路)

    题目链接:http://poj.org/problem?id=2438 本文链接:http://www.cnblogs.com/Ash-ly/p/5452615.html 题意: 有2*N个小朋友要坐 ...

  4. Codeforces #442 Div2 F

    #442 Div2 F 题意 给出一些包含两种类型(a, b)问题的问题册,每本问题册有一些题目,每次查询某一区间,问有多少子区间中 a 问题的数量等于 b 问题的数量加 \(k\) . 分析 令包含 ...

  5. hihocoder Popular Products(STL)

    Popular Products 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 Given N lists of customer purchase, your tas ...

  6. rsync用于同步目录

    rsync是unix/linux下同步文件的一个高效算法,它能同步更新两处计算机的文件与目录,并适当利用查找文件中的不同块以减少数据传输.rsync中一项与其他大部分类似程序或协定中所未见的重要特性是 ...

  7. mfc afxbeginthread()

    在进行多线程程序设计的时候,我们经常用到AfxBeginThread函数来启动一条线程该函数使用起来非常的简单方便,其定义如下 CWinThread* AfxBeginThread(   AFX_TH ...

  8. linux-文件中行按照出现次数多少排序

    cat sorttest | sort | uniq -c | sort -k1 sorttest内容如下:

  9. 【java 正则表达式】记录所有在java中使用正则表达式的情况

    本篇记录在java中邂逅正则表达式的所有美丽瞬间.因为在java和js中正则表达式的语法并不一致. 1.匹配字符串中有出现[2.1开头或者&2.1或者&3.1等的] Pattern m ...

  10. SqlServer_删除重复行只保留一条记录

      前提:相同的数据重复往数据库写入,导致存在仅主键Id不同的重复数据,现在需要去除重复数据,仅保留重复数据中Id最大的一条   思路: 1.找出存在重复数据的记录,并取重复数据中最大的Id值 2.删 ...