您的位置:首页 > 其它

.NET 图片双线性插值缩放算法

2013-03-28 10:44 127 查看
不放首页,都木有人看的说。。。

之前公司搞图像处理,代码都拷不出来,只剩下一点点自己平时找的和写的了。

代码全是自己写的,原理嘛,,都是从c++,java里边学来的。

/// <summary>
/// 双线性插值缩放算法
/// </summary>
/// <param name="srcImg"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static Image Thumbnail(Bitmap srcImg, Int32 width, Int32 height)
{
var srcData = srcImg.LockBits(new Rectangle(0, 0, srcImg.Width, srcImg.Height), ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);

var destImg = new Bitmap(width, height, PixelFormat.Format24bppRgb);
var destData = destImg.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
Int32 x, y;
Double sx, sy, u, v;
var pm = new Double[4];

Double w = (Double)srcImg.Width / (Double)width;
Double h = (Double)srcImg.Height / (Double)height;

for (int row = 0; row < height; row++)
{
sy = (Double)(row + 0.5) * h - 0.5;
y = (Int32)sy;
if (y > sy)
y--;
v = sy - y;
for (int col = 0; col < width; col++)
{
var color = new List<Byte>();
sx = (Double)(col + 0.5) * w - 0.5;
x = (Int32)sx;
if (x > sx)
x--;
u = sx - x;

pm[0] = (1.0 - u) * (1.0 - v);
pm[1] = v * (1.0 - u);
pm[2] = u * (1.0 - v);
pm[3] = u * v;

for (int n = 0; n < 4; n++)
{
Int32 xx = (n == 0 || n == 1) ? x : x + 1;
if (xx < 0)
xx = 0;
else if (xx > srcImg.Width - 1)
xx = srcImg.Width - 1;
Int32 yy = (n == 0 || n == 2) ? y : y + 1;
if (yy < 0)
yy = 0;
else if (yy > srcImg.Height - 1)
yy = srcImg.Height - 1;

Byte* srcPoint = (Byte*)srcData.Scan0 + xx * 3 + yy * srcData.Stride;
color.Add(srcPoint[0]);
color.Add(srcPoint[1]);
color.Add(srcPoint[2]);
}

Byte* destPoint = (Byte*)destData.Scan0 + col * 3 + row * destData.Stride;
destPoint[0] = (Byte)(pm[0] * color[0] + pm[1] * color[3] + pm[2] * color[6] + pm[3] * color[9]);
destPoint[1] = (Byte)(pm[0] * color[1] + pm[1] * color[4] + pm[2] * color[7] + pm[3] * color[10]);
destPoint[2] = (Byte)(pm[0] * color[2] + pm[1] * color[5] + pm[2] * color[8] + pm[3] * color[11]);
}
}

destImg.UnlockBits(destData);
srcImg.UnlockBits(srcData);
return destImg;
}


效果还是不错滴。额。里边处理的都是24位彩图。用的都是unsafe代码,没感觉到比c++慢多少。。- -
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: