您的位置:首页 > 移动开发 > Android开发

【Android图像处理】几种压缩图像的算法

2016-11-19 16:53 357 查看
我们要知道,任何一款图像处理的app在进行图片处理的时候都会进行压缩。

为什么?

为了更快的速度。现在手机的处理器已经非常强悍了,但是在进行超高清图片处理的时候需要进行大量的矩阵运算,耗时会非常的长,要明白的一点是手机处理器再好和电脑处理器还是没法比的。因此,在进行图片处理的时候对图片进行压缩是必须也是必要的。

下面介绍第一种压缩算法

将图片压缩至480 * 480 以内

算法如下:

/***
* 图片压缩
* @param bgimage 源图片资源
* @return 宽高比例不变,且都在480以内的图片
*/
public static Bitmap zoomImage(Bitmap bgimage) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();

double newWidth = width;
double newHeight = height;

int Max = (int) Math.max(newWidth, newHeight);
int flag = 0;//默认 h > w

if(newWidth > newHeight){
flag = 1;
}

if(Max > 480 && flag == 0){//height > width
newHeight = 480;
newWidth = 480 * 1.0f / height * width;
}else if(Max > 480 && flag == 1){//width > height
newWidth = 480;
newHeight = 480 * 1.0f / width * height;
}

// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}
一般手机拍摄的图片都是高>宽,但是也有例外,比如横着拍的时候就不是这样。目前手机屏幕的主流分辨率为1980* 1080,也就是所谓的1080p,640 * 960的照片就已经很清楚了。这里我压缩到480*480以内是为了处理得更快。

下面介绍第二种压缩算法:

将图片压缩至指定大小,其算法如下:

/**
* 压缩图片至指定大小
* @param bgimage
* @param newWidth 新的宽度
* @param newHeight 新的高度
* @return
*/
public static Bitmap zoomImage1(Bitmap bgimage,double newWidth,double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();

// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}
其实这个算法还有待改进,因为这样会使原图的宽高的比例发生变化。
解决方案:只传入宽或高,另一个边长根据原图去计算,这样压缩不会改变图片的比例。

下面就是第三种压缩算法:

截取的示意图如下:



将一张图片截取成宽高相等的图片,这个就和图片切块算法类似了。算法如下:

/**
* 将bitmap压缩成w = h的新图片(截取)
* @param bitmap
* @return result w = h的图片
*/
public static Bitmap toSquare(Bitmap bitmap){
int w = bitmap.getWidth();
int h = bitmap.getHeight();

Bitmap result = null;

int flag = 0;//默认 h > w
if(w > h)//h < w
flag = 1;

if(flag == 0){//h > w
int s = (int) ((h - w) * 1.0 / 2);
result = Bitmap.createBitmap(bitmap, 0, s, w, w);
}else{//h < w
int s = (int) ((w - h) * 1.0 / 2);
result = Bitmap.createBitmap(bitmap, s, 0, w, w);
}
return result;
}
压缩的算法其实还有很多...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息