Android View截屏长图拼接(RecyclerView)
我们在实际使用中,往往图片转化成Bitmap,对Bitmap操作的时候(如:截屏分享等),可能Bitmap会过大,导致无视实现对应功能。那么我们就需要对Bitmap进行压缩处理。
public static Bitmap compressBitmap(Bitmap bitmap, int maxSize) {
Bitmap newBitmap;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;//为true的时候表示只读边,不读内容
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;//当系统内存不够时候图片自动被回收
// Do not compress
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//如果使用ARGB-8888连续压缩两个10M图分分钟oom,而使用4444比565还糊。。
long length = baos.toByteArray().length;
if (length / 1024 > 4 * 1024) {
int a = 2;
while (length / 1024 / a > 4 * 1024) {
a = a + 1;
}
newOpts.inSampleSize = a;
} else {
newOpts.inSampleSize = 1;
}
newBitmap = BitmapFactory.decodeStream(inputStream, new Rect(), newOpts);
if (maxSize > 100) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int options = 100;
newBitmap.compress(Bitmap.CompressFormat.PNG, options, byteArrayOutputStream);
if (byteArrayOutputStream.toByteArray().length / 1024 > maxSize) {
while (byteArrayOutputStream.toByteArray().length / 1024 > maxSize) {
// Clean up os
byteArrayOutputStream.reset();
// interval 10
options -= 5;
newBitmap.compress(Bitmap.CompressFormat.PNG, options, byteArrayOutputStream);
}
byte[] bytes = byteArrayOutputStream.toByteArray();
newBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
FileFileUtils.closeSilently(byteArrayOutputStream);
}
FileFileUtils.closeSilently(baos);
FileFileUtils.closeSilently(inputStream);
return newBitmap;
}
public static void closeSilently(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// Do nothing
}
}