原理:图片缩放的原理,我的理解,就是把图片放在一个二维平面坐标系里,图片的缩放,其实是图片所有点的坐标缩放。
等比例缩放,就是设定宽高和原始宽高的比例不变。scale=destnation/old;
方法
核心参数:原始宽高,设定宽高,设定宽高与原始宽高的比例。
核心方法:
matrix.postScale(scale_w, scale_h); Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, old_w, old_h, matrix,true);
默认以左上角(0,0)为原点。

核心代码:
//decode to bitmap
Bitmap bitmap = BitmapFactory.decodeFile(path);
//实际宽高
int src_w = bitmap.getWidth();
int src_h = bitmap.getHeight();
int dst_w = src_w;
int dst_h = src_h;
//限定宽高
int maxWidth = 1900;
int maxHeight = 1000;
//宽高缩放比例
float scale_w = ((float) dst_w) / src_w;
float scale_h = ((float) dst_h) / src_h;
Matrix matrix = new Matrix();
matrix.postScale(scale_w, scale_h);
Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,true);
//质量压缩
ByteArrayOutputStream baos = new ByteArrayOutputStream();
dstbmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] bytes = baos.toByteArray();*
思路:
图片的宽高缩放是使用createBitmap(),所以需要将图片转成bitmap,并获取满足设定宽高的宽高比。
函数:
public static String getImageBase64(String path) {
//decode to bitmap
Bitmap bitmap = BitmapFactory.decodeFile(path);
//将图片的宽高限定在1920x1080,
//实际宽高
int src_w = bitmap.getWidth();
int src_h = bitmap.getHeight();
int dst_w = src_w;
int dst_h = src_h;
//限定宽高
int maxWidth = 1900;
int maxHeight = 1000;
//等比例缩放
if (dst_w > maxWidth) {
float scale = (float) (maxWidth) / (float) (dst_w);
dst_w = maxWidth;
dst_h = (int) (dst_h * scale);
}
if (dst_h > maxHeight) {
double scale = (float) (maxHeight) /(float) ( dst_h);
dst_h = maxHeight;
dst_w = (int) (dst_w * scale);
}
float scale_w = ((float) dst_w) / src_w;
float scale_h = ((float) dst_h) / src_h;
Matrix matrix = new Matrix();
matrix.postScale(scale_w, scale_h);
Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,true);
//convert to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
dstbmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] bytes = baos.toByteArray();
//base64 encode
byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
String encodeString = new String(encode);
return encodeString;
}