Android(安卓)图像缩略图及压缩图像
16lz
2021-01-24
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) { }}
更多相关文章
- android消除锯齿原理分析
- Android将camera获取到的YuvData在jni中转化为Mat方法
- Android(安卓)异步加载图像优化,如:引入线程池、引入缓存
- Android(安卓)Glide v4使用(基础篇)
- Adobe 全线触屏应用搬上 Android(安卓)Market
- android桌面文件夹美化
- android摄像头获取图像——第二弹
- android 自定义图形之层叠样式 [layer-list] 的使用
- Android(安卓)Nine-patch