1,调用系统照相机并将照片保存在指定的目录下
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File baseFile = FileHelper.getPicBaseFile();
String fileName = getFileName(); // 文明名
temImgName = fileName;
imgFile = new File(baseFile, fileName); //保存图片的路径
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(imgFile));
startActivityForResult(takePictureIntent, Constant.CAMERA_REQUEST);
代码解释:FileHelper为文件的帮助类,控制文件的基本信息
import java.io.File;
import android.os.Environment;
/**
* 图片路径以及数据库路径的处理
*
* @author Administrator
*
*/
public class FileHelper {
private static final String PICFILEPATH = "colectSite/image";
private static final String DATAFILEPATH = "colectSite/data"; // 数据库文件路径
private static final String DATANAME = "sites.db"; // 数据库名称
private static final String COMPRESS_PICFILEPATH = "colectSite/com_image";
/**
* 获得压缩图片保存的基础路径
* @return
*/
public static File getCompressPicBaseFile(){
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 文件可用使用外部存储
File f = new File(Environment.getExternalStorageDirectory(),
COMPRESS_PICFILEPATH);
if (!f.exists()) {
f.mkdirs();
}
return f;
} else if ((new File("/mnt/sdcard2")).exists()) {
String file = "/mnt/sdcard2/" + COMPRESS_PICFILEPATH;
File f = new File(file);
if (!f.exists()) {
f.mkdirs();
}
return f;
} else {
return null;
} }
/**
* 图片基础路径
*
* @return
*/
public static File getPicBaseFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 文件可用使用外部存储
File f = new File(Environment.getExternalStorageDirectory(),
PICFILEPATH);
if (!f.exists()) {
f.mkdirs();
}
return f;
} else if ((new File("/mnt/sdcard2")).exists()) {
String file = "/mnt/sdcard2/" + PICFILEPATH;
File f = new File(file);
if (!f.exists()) {
f.mkdirs();
}
return f;
} else {
return null;
}
}
/**
*
* @return 数据库文件路径
*/
public static File getDBFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 文件可用使用外部存储
File f = new File(Environment.getExternalStorageDirectory(),
DATAFILEPATH);
if (!f.exists()) {
f.mkdirs();
}
return new File(f,DATANAME);
} else if ((new File("/mnt/sdcard2")).exists()) {
String file = "/mnt/sdcard2/" + DATAFILEPATH;
File f = new File(file);
if (!f.exists()) {
f.mkdirs();
}
return new File(f,DATANAME);
} else {
return null;
}
}
}
2,在界面中显示图片,如果过多加载图片可能会导致内存溢出,所以需要采用BitmapFactroy.option 来获得对应分辨率(手机的分辨率或者图片空间的大小)的图片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 返回的data是被压缩过的图片,图片太小,我们需要显示较大的图片
if (requestCode == Constant.CAMERA_REQUEST && resultCode == RESULT_OK) { // 需要显示图片信息
Bitmap bitmap = ImageHelper.createImage(imgFile.toString());
img_site.setImageBitmap(bitmap);
//保存压缩图片
File compressFile = new File(FileHelper.getCompressPicBaseFile(), temImgName);
ImageHelper.saveCompressBitmap(bitmap, compressFile);
imageName = temImgName;
btn_takePhoto.setText(getResources().getString(
R.string.re_take_photo));
}
super.onActivityResult(requestCode, resultCode, data);
}
代码解释:ImageHelper为图片帮助类,负责处理图片的各种工作
package com.sunbird.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//创建本地的图片
public class ImageHelper {
/**
* @param filePath
* 本地保存的文件路径
* @return 返回压缩过的图片
*/
public static Bitmap createSmallImage(String filePath) {
Bitmap bitmap = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 150 * 150);
opts.inJustDecodeBounds = false;
try {
bitmap = BitmapFactory.decodeFile(filePath, opts);
} catch (Exception e) {
// TODO: handle exception
}
return bitmap;
}
/**
* 保存压缩的图片
* @param bitmap 需要保存的图片
* @param file 图片的保存完整路径
* @return true 保存成功 ,false 否则保存失败
*/
public static boolean saveCompressBitmap(File file) {
FileOutputStream fileOutputStream = null;
Bitmap bitmap = createImage(file.toString());
try {
fileOutputStream = new FileOutputStream(file);
return bitmap.compress(Bitmap.CompressFormat.JPEG, 90,
fileOutputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(fileOutputStream != null){
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/**
* 保存压缩的图片
* @param bitmap 需要保存的图片
* @param file 图片的保存完整路径
* @return true 保存成功 ,false 否则保存失败
*/
public static boolean saveCompressBitmap(Bitmap bitmap, File file) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
return bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
fileOutputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(fileOutputStream != null){
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/**
* 创建800*480分辨率的图片
* @param filePath
* @return
*/
public static Bitmap createImage(String filePath) {
Bitmap bitmap = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 800 * 480);
opts.inJustDecodeBounds = false;
try {
bitmap = BitmapFactory.decodeFile(filePath, opts);
} catch (Exception e) {
// TODO: handle exception
}
return bitmap;
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
/**
* Decode and sample down a bitmap from a file to the requested width and
* height.
*
* @param filename
* The full path of the file to decode
* @param reqWidth
* The requested width of the resulting bitmap
* @param reqHeight
* The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect
* ratio and dimensions that are equal to or greater than the
* requested width and height
*/
public static Bitmap decodeSamllBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options}
* object when decoding bitmaps using the decode* methods from
* {@link BitmapFactory}. This implementation calculates the closest
* inSampleSize that will result in the final decoded bitmap having a width
* and height equal to or larger than the requested width and height. This
* implementation does not ensure a power of 2 is returned for inSampleSize
* which can be faster when decoding but results in a larger bitmap which
* isn't as useful for caching purposes.
*
* @param options
* An options object with out* params already populated (run
* through a decode* method with inJustDecodeBounds==true
* @param reqWidth
* The requested width of the resulting bitmap
* @param reqHeight
* The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee a final image
// with both dimensions larger than or equal to the requested height
// and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger
// inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
关于计算SampleSize的大小在上述的方法中都可以使用,有英文注释的部分为帮助文档的计算方法,其他的为在网上看到的计算方法,个人根据情况自行选择。