sFormat.JPEG, 100, baos);
? ? ? ? int options = 100;
? ? ? ? // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
? ? ? ? while (baos.toByteArray().length / 1024 > size) {
? ? ? ? ? ? // 重置baos即清空baos
? ? ? ? ? ? baos.reset();
? ? ? ? ? ? // 每次都减少10
? ? ? ? ? ? options -= 10;
? ? ? ? ? ? // 这里压缩options%,把压缩后的数据存放到baos中
? ? ? ? ? ? image.compress(Bitmap.CompressFormat.JPEG, options, baos);
?
? ? ? ? }
? ? ? ? // 把压缩后的数据baos存放到ByteArrayInputStream中
? ? ? ? ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
? ? ? ? // 把ByteArrayInputStream数据生成图片
? ? ? ? Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
? ? ? ? return bitmap;
? ? }
?
}
下面是布局,很简单
? ? xmlns:tools="http://schemas.android.com/tools"
? ? android:layout_width="match_parent"
? ? android:layout_height="match_parent"
? ? tools:context="${relativePackage}.${activityClass}" >
?
? ? ? ? ? ? android:id="@+id/imageView1"
? ? ? ? android:layout_width="200dp"
? ? ? ? android:layout_height="200dp"
? ? ? ? android:layout_alignParentTop="true"
? ? ? ? android:layout_centerHorizontal="true"
? ? ? ? android:layout_marginTop="64dp"
? ? ? ? android:src="@drawable/ic_launcher" />
?
? ? ? ? ? ? android:id="@+id/button1"
? ? ? ? android:layout_width="wrap_content"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:layout_below="@+id/imageView1"
? ? ? ? android:layout_centerHorizontal="true"
? ? ? ? android:layout_marginTop="32dp"
? ? ? ? android:text="拍照" />
?
最后注意,一定要在AndroidManifest.xml添加SD卡访问权限: