最近公司的项目需要开发类似友盟的社会化分享组件,在编码中发现QQ、微信、新浪、钉钉等分享SDK,对byte数组或者bitmap形式的缩略图有大小限制,否则会报分享失败。下面是具体的代码:
/** * 图片的缩放方法 * * @param bitmap :源图片资源 * @param maxSize :图片允许最大空间 单位:KB * @return */ public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) { if (null == bitmap) { return null; } if (bitmap.isRecycled()) { return null; } // 单位:从 Byte 换算成 KB double currentSize = bitmapToByteArray(bitmap, false).length / 1024; // 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩 while (currentSize > maxSize) { // 计算bitmap的大小是maxSize的多少倍 double multiple = currentSize / maxSize; // 开始压缩:将宽带和高度压缩掉对应的平方根倍 // 1.保持新的宽度和高度,与bitmap原来的宽高比率一致 // 2.压缩后达到了最大大小对应的新bitmap,显示效果最好 bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple)); currentSize = bitmapToByteArray(bitmap, false).length / 1024; } return bitmap; } /** * 图片的缩放方法 * * @param orgBitmap :源图片资源 * @param newWidth :缩放后宽度 * @param newHeight :缩放后高度 * @return */ public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) { if (null == orgBitmap) { return null; } if (orgBitmap.isRecycled()) { return null; } if (newWidth <= 0 || newHeight <= 0) { return null; } // 获取图片的宽和高 float width = orgBitmap.getWidth(); float height = orgBitmap.getHeight(); // 创建操作图片的matrix对象 Matrix matrix = new Matrix(); // 计算宽高缩放率 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true); return bitmap; } /** * bitmap转换成byte数组 * * @param bitmap * @param needRecycle * @return */ public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) { if (null == bitmap) { return null; } if (bitmap.isRecycled()) { return null; } ByteArrayOutputStream output = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); if (needRecycle) { bitmap.recycle(); } byte[] result = output.toByteArray(); try { output.close(); } catch (Exception e) { Log.e(TAG, e.toString()); } return result; }
参考链接: