Android可以通过调用系统摄像头来获取图像,由于拍照的图像太大会造成java.lang.OutOfMemoryError错误。为了避免这种情况发生,可以通过缩略图的方式来分配更少的内存,即以牺牲图像的质量为代价。

    缩略图主要通过BitmapFactory.Options来实现。

    如果该值设为true,那么将不返回实际的bitmap,也不给其分配内存空间,这样就避免内存溢出。当允许读取图像的信息如图像大小。

    BitmapFactory.Options options;

    options.outHeight  图像原始高度

    options.outWidth   图像原始宽度

    通过options.inSampleSize来实现缩放。

     如果值设置为>1,要求解码器解码出原始图像的一个子样本,返回一个较小的bitmap,以节省存储空间。

    例如,inSampleSize == 2,则取出的缩略图的宽和高都是原始图像的1/2,图像的大小为原始图像的1/4。对于任何值<=1的同样处置为1。这里要注意的是,inSampleSize可能小于0,必须做判断。

    具体步骤如下:

    1、通过调用系统摄像头获取图像

String photoPath;SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");String path = Environment.getExternalStorageDirectory().getPath()+ "/";Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);String photoName = formatter.format(new Date()) + ".jpg";photoPath = path + photoName;Uri uri = Uri.fromFile(new File(path, photoName));intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, requestCode);

    2、如果为竖屏拍照,需要对图像进行旋转处理

private int getRotationForImage(String path) {int rotation = 0;try {ExifInterface exifInterface = new ExifInterface(path);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:rotation = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:rotation = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:rotation = 270;break;default:rotation = 0;}} catch (IOException e) {e.printStackTrace();}return rotation;}
    public static Bitmap rotaingBitmap(int angle , Bitmap bitmap) {         //旋转图片动作          Matrix matrix = new Matrix();;         matrix.postRotate(angle);        //创建新的图片          Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);        return resizedBitmap;      }
    3、压缩并保持图像

public void saveCompress(Bitmap bitmap, String filepath) {    File file = new File(filepath);    try {    FileOutputStream out = new FileOutputStream(file);    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out)) { //40是压缩率,表示压缩60%,如果不压缩为100,表示压缩率为0out.flush();    out.close(); }}catch (Exception e) {   }}


更多相关文章

  1. android消除锯齿原理分析
  2. Android将camera获取到的YuvData在jni中转化为Mat方法
  3. Android(安卓)异步加载图像优化,如:引入线程池、引入缓存
  4. Android(安卓)Glide v4使用(基础篇)
  5. Adobe 全线触屏应用搬上 Android(安卓)Market
  6. android桌面文件夹美化
  7. android摄像头获取图像——第二弹
  8. android 自定义图形之层叠样式 [layer-list] 的使用
  9. Android(安卓)Nine-patch

随机推荐

  1. Xposed 实现给Hook的APP动态添加权限Perm
  2. Android(安卓)-- 工程目录解释
  3. Android布局案例之人人android九宫格
  4. Android开机速度 ------之ART预优化dex2o
  5. Android常用之Butterknife使用详解
  6. Android之简单了解Android OS内部机制
  7. Android中 在显示ImageView时图片上面和
  8. Android(安卓)init 详细过程分析
  9. 【转】获取android设备 id
  10. PC_android通信之传输图片并显示在手机端