Android 图像缩略图及压缩图像

    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,表示压缩率为0

				out.flush();    
				out.close(); 
			}
		}catch (Exception e) {  
			 
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值