Android拍照、相册选取、裁剪图片

来自:http://blog.csdn.net/ryantang03/article/details/8656278


package com.example.listactivity;

import java.io.ByteArrayOutputStream;
import java.io.File;

import com.example.model.ImageTools;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class Paizhao extends Activity {

private ImageView paizhao;
private static final int SCALE = 5;//照片缩小比例
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.paizhao);
paizhao = (ImageView)this.findViewById(R.id.paizhao);
paizhao.setOnClickListener(new TanDialog());
}

class TanDialog implements OnClickListener{

@Override
public void onClick(View v) {
showPicturePicker(Paizhao.this);
}

}

private void showPicturePicker(Context context) {

AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("图片来源");
dialog.setNegativeButton("取消", null);
dialog.setItems(new String[]{"拍照","相册"},new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
int REQUEST_CODE;
switch(which){

//拍照
case 0:
REQUEST_CODE =0;
//启动相机
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
SharedPreferences share = getSharedPreferences("temp", Context.MODE_WORLD_WRITEABLE);
ImageTools.deletePhotoAtPathAndName(Environment.getExternalStorageDirectory().getAbsolutePath(), share.getString("tempName", ""));

String filename = String.valueOf(System.currentTimeMillis())+".jpg";
Editor editor = share.edit();
editor.putString("tempName", filename);
editor.commit();

Uri imguri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),filename));
//开启
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imguri);
startActivityForResult(openCameraIntent, REQUEST_CODE);
break;

//相册
case 1:
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(openAlbumIntent, 0);
break;
}

}
} );
dialog.create().show();

}

@Override
//照相以后返回的照片
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){

switch (requestCode) {
//拍照
case 0:
Uri uri = null;
if(data != null){
uri = data.getData();
Log.e("----?", "data");
}else{
Log.e("----?", "file");
String fileName = getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE).getString("tempName", "");
uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName));
}
//剪裁
cropImage(uri, 500, 500, 1);
break;
case 1:
Bitmap photo = null;
Uri photoUri = data.getData();
if (photoUri != null) {
photo = BitmapFactory.decodeFile(photoUri.getPath());
}
if (photo == null) {
Bundle extra = data.getExtras();
if (extra != null) {
photo = (Bitmap)extra.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
}
}
paizhao.setImageBitmap(photo);
break;
}
}
}

//截取图片
public void cropImage(Uri uri, int outputX, int outputY, int requestCode){
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", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("outputFormat", "JPEG");
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, requestCode);
}

}

ImageTools 类


package com.example.model;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
* Tools for handler picture
*
* @author Ryan.Tang
*
*/
public final class ImageTools {

/**
* Transfer drawable to bitmap
*
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();

Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}

/**
* Bitmap to drawable
*
* @param bitmap
* @return
*/
public static Drawable bitmapToDrawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
}

/**
* Input stream to bitmap
*
* @param inputStream
* @return
* @throws Exception
*/
public static Bitmap inputStreamToBitmap(InputStream inputStream)
throws Exception {
return BitmapFactory.decodeStream(inputStream);
}

/**
* Byte transfer to bitmap
*
* @param byteArray
* @return
*/
public static Bitmap byteToBitmap(byte[] byteArray) {
if (byteArray.length != 0) {
return BitmapFactory
.decodeByteArray(byteArray, 0, byteArray.length);
} else {
return null;
}
}

/**
* Byte transfer to drawable
*
* @param byteArray
* @return
*/
public static Drawable byteToDrawable(byte[] byteArray) {
ByteArrayInputStream ins = null;
if (byteArray != null) {
ins = new ByteArrayInputStream(byteArray);
}
return Drawable.createFromStream(ins, null);
}

/**
* Bitmap transfer to bytes
*
* @param byteArray
* @return
*/
public static byte[] bitmapToBytes(Bitmap bm) {
byte[] bytes = null;
if (bm != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
bytes = baos.toByteArray();
}
return bytes;
}

/**
* Drawable transfer to bytes
*
* @param drawable
* @return
*/
public static byte[] drawableToBytes(Drawable drawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
byte[] bytes = bitmapToBytes(bitmap);
;
return bytes;
}

/**
* Base64 to byte[]
// */
// public static byte[] base64ToBytes(String base64) throws IOException {
// byte[] bytes = Base64.decode(base64);
// return bytes;
// }
//
// /**
// * Byte[] to base64
// */
// public static String bytesTobase64(byte[] bytes) {
// String base64 = Base64.encode(bytes);
// return base64;
// }

/**
* Create reflection images
*
* @param bitmap
* @return
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int w = bitmap.getWidth();
int h = bitmap.getHeight();

Matrix matrix = new Matrix();
matrix.preScale(1, -1);

Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w,
h / 2, matrix, false);

Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2),
Config.ARGB_8888);

Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);

canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);

Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, h, w, bitmapWithReflection.getHeight()
+ reflectionGap, paint);

return bitmapWithReflection;
}

/**
* Get rounded corner images
*
* @param bitmap
* @param roundPx
* 5 10
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

return output;
}

/**
* Resize the bitmap
*
* @param bitmap
* @param width
* @param height
* @return
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}

/**
* Resize the drawable
* @param drawable
* @param w
* @param h
* @return
*/
public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap oldbmp = drawableToBitmap(drawable);
Matrix matrix = new Matrix();
float sx = ((float) w / width);
float sy = ((float) h / height);
matrix.postScale(sx, sy);
Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(newbmp);
}

/**
* Get images from SD card by path and the name of image
* @param photoName
* @return
*/
public static Bitmap getPhotoFromSDCard(String path,String photoName){
Bitmap photoBitmap = BitmapFactory.decodeFile(path + "/" +photoName +".png");
if (photoBitmap == null) {
return null;
}else {
return photoBitmap;
}
}

/**
* Check the SD card
* @return
*/
public static boolean checkSDCardAvailable(){
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}

/**
* Get image from SD card by path and the name of image
* @param fileName
* @return
*/
public static boolean findPhotoFromSDCard(String path,String photoName){
boolean flag = false;

if (checkSDCardAvailable()) {
File dir = new File(path);
if (dir.exists()) {
File folders = new File(path);
File photoFile[] = folders.listFiles();
for (int i = 0; i < photoFile.length; i++) {
String fileName = photoFile[i].getName().split("\\.")[0];
if (fileName.equals(photoName)) {
flag = true;
}
}
}else {
flag = false;
}
// File file = new File(path + "/" + photoName + ".jpg" );
// if (file.exists()) {
// flag = true;
// }else {
// flag = false;
// }

}else {
flag = false;
}
return flag;
}

/**
* Save image to the SD card
* @param photoBitmap
* @param photoName
* @param path
*/
public static void savePhotoToSDCard(Bitmap photoBitmap,String path,String photoName){
if (checkSDCardAvailable()) {
File dir = new File(path);
if (!dir.exists()){
dir.mkdirs();
}

File photoFile = new File(path , photoName + ".png");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(photoFile);
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
fileOutputStream.flush();
// fileOutputStream.close();
}
}
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
e.printStackTrace();
} finally{
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* Delete the image from SD card
* @param context
* @param path
* file:///sdcard/temp.jpg
*/
public static void deleteAllPhoto(String path){
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
}

public static void deletePhotoAtPathAndName(String path,String fileName){
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
if (files[i].getName().equals(fileName)) {
files[i].delete();
}
}
}
}

}

AndroidManifest


       <uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android拍照、相册选取、裁剪图片,布布扣,bubuko.com

时间: 2024-10-13 02:39:57

Android拍照、相册选取、裁剪图片的相关文章

Android从相册中获取图片以及路径

首先是相册图片的获取: private final String IMAGE_TYPE = "image/*"; private final int IMAGE_CODE = 0;   //这里的IMAGE_CODE是自己任意定义的 //使用intent调用系统提供的相册功能,使用startActivityForResult是为了获取用户选择的图片 Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); getAlbum.set

调用 android 系统拍照结合 android-crop 裁剪图片

在一个应用中更换用户的头像,一般有拍照和从图库中选择照片两种方法,现在网上也有很多开源的,但是很多都太复杂.而 Android-crop 这个库比较小,代码不复杂,比较适合,但是它没有拍照这个功能,需要我们自己整合进去. 调用系统相机拍照 返回略缩图的拍照 // 调用系统的拍照 private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTU

android 从相册中选择图片并判断图片是否旋转

今天在做图片合成时,首先从相册中选择图片,然后判断该图片是否旋转了,今天就讲下图片是否旋转,直接上代码 /** * 读取照片exif信息中的旋转角度 * * @param path * 照片路径 * @return角度 获取从相册中选中图片的角度 */ public static int readPictureDegree(String path) { if (TextUtils.isEmpty(path)) { return 0; } int degree = 0; try { ExifInt

Android 拍照后保证保证图片不失真,进行压缩

今天在网上找了一下参考,得出把图片压缩至KB 其他不想多说.直接上代码 拍完照后调用下面代码 BitmapUtils.compressBitmap(photoPath, photoPath, 640);  //压缩 这是个工具类. package com.continuouscamera; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import

Android 拍照图片选取与图片剪裁

最近从以前的项目中扒下来一个常用的模块,在这里有必要记录一下的,就是android上获取图片以及裁剪图片,怎么样?这个功能是不是很常用啊,你随便打开一个App,只要它有注册功能都会有设置人物头像的功能,尤其在内容型的app中更为常见,那么这些功能是怎么实现的呢?今天,在这里就记录一下好了,防止以后的项目中也会用到,就直接拿来用好了. 1.通过拍照或者图册获取图片(不需要剪裁) 这种获取图片的方式就比较次了,因为不设置图片的剪裁功能,有可能因为图片过大,导致OOM,但是这种方式也是有必要讲一下的,

android拍照图片选取与图片剪裁

转载请注明出处:http://blog.csdn.net/allen315410/article/details/39994913 最近从以前的项目中扒下来一个常用的模块,在这里有必要记录一下的,就是android上获取图片以及裁剪图片,怎么样?这个功能是不是很常用啊,你随便打开一个App,只要它有注册功能都会有设置人物头像的功能,尤其在内容型的app中更为常见,那么这些功能是怎么实现的呢?今天,在这里就记录一下好了,防止以后的项目中也会用到,就直接拿来用好了. 1.通过拍照或者图册获取图片(不

android拍照获得图片及获得图片后剪切设置到ImageView

ok,这次的项目需要用到设置头像功能,所以做了个总结,直接进入主题吧. 先说说怎么 使用android内置的相机拍照然后获取到这张照片吧 直接上代码: Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/zxy/image/temp.png&qu

android手机拍照或选取相册里面的图片

three.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"

Android拍照、相册 获取图片后,裁剪图片

最近在做的B2B的项目,图片大部分来源于用户自己上传: 由于android尺寸的不一,用户相机,相册的图片也是奇形怪状: 所以在上传之前对图片做一次裁剪是很有必要的! 下面是按比例裁剪图片的demo 资源文件activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/