微信规定,分享小程序展示的图片应该在 128KB 以内,同时图片默认展示比例为 5:4。
所以需要对传入的图片进行裁剪和压缩。关于图片压缩有个很大的坑,改了一晚上才好,所以记录一下,先填坑以后再优化。
参考了其他大神的博客,整理出了下面具体的实现方法:
方法一:
/**
* 按5:4裁切图片
*/
private static Bitmap cropImage5To4(Bitmap srcBitmap) {
if (srcBitmap == null) {
return null;
}
int w = srcBitmap.getWidth(); // 得到图片的宽,高
int h = srcBitmap.getHeight();
float srcW = w > h * 1.25f ? h * 1.25f : w;
float srcH = w > h * 1.25f ? h : w / 1.25f;
float retX = w > h * 1.25f ? (w - h * 1.25f) / 2 : 0;//居中裁剪
float retY = w > h * 1.25f ? 0 : (h - w / 1.25f) / 2f;
//以下这句是关键
return Bitmap.createBitmap(srcBitmap, Math.round(retX), Math.round(retY), Math.round(srcW), Math.round(srcH), null, false);
}
/**
* 判断图片类型
*/
public static int getPicTypeByUrl(String url) {
int picType = -1;
if (url == null)