昨天去面试遇到了这么一道题,回来就按插值算法写了下,代码如下:
public Image zoomImage(Image src, int desW, int desH) {
Image returnImg = null;
int srcW = src.getWidth();// 源图片的宽
int srcH = src.getHeight();// 源图片的高
int srcPix[] = new int[srcW * srcH];// 存储源图片像素点信息的数组
int tabY[] = new int[desH];// 转成目标图片使用的存储插值横行信息的插值表
int tabX[] = new int[desW];// 转成目标图片使用的存储插值竖行信息的插值表
int distance;// 在做插值表的时候根据源图和目标图比较,看那个长度作为标准
/*
* ========================================基础变量==========================
*/
src.getRGB(srcPix, 0, srcW, 0, 0, srcW, srcH);// 将源图片像素信息转存至srcPix数组
distance = srcH > desH ? srcH : desH;// 哪个大哪个作为标准
int sPoint = 0;
int dPoint = 0;
int sFoot = 0;
int dFoot = 0;
for (int i = 0; i <= distance; i++) {
tabY[dPoint] = sPoint;
sFoot += srcH;
dFoot += desH;
if (sFoot > distance) {
sPoint++;
sFoot -= distance;
}
if (dFoot > distance) {
dPoint++;
dFoot -= distance;
}
}
sPoint = 0;
dPoint = 0;
sFoot = 0;
dFoot = 0;
distance = srcW > desW ? srcW : desW;
for (int i = 0; i <= distance; i++) {
tabX[dPoint] = sPoint;
sFoot += srcW;
dFoot += desW;
if (sFoot > distance) {
sPoint++;
sFoot -= distance;
}
if (dFoot > distance) {
dPoint++;
dFoot -= distance;
}
}
/*-------------------插值表录入完成-----------------*/
int desPix[] = new int[desW * desH];
int mubSH = 0;
int mubDH = 0;
int remDYP = -1;// 记录插值表Y到哪个点了。
for (int i = 0; i < desH; i++) {
if (remDYP == tabY[i]) {
System.arraycopy(desPix, mubDH - desW, desPix, mubDH, desW);
} else {
for (int j = 0; j < desW; j++) {
desPix[mubDH + j] = srcPix[mubSH + tabX[j]];
}
mubSH += srcW;
remDYP = tabY[i];
}
mubDH += desW;
}
returnImg = Image.createRGBImage(desPix, desW, desH, false);
return returnImg;
}