110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 获取图像的马赛克图像
/// </summary>
/// <param name="imgSrc">原始图像</param>
/// <param name="width">马赛克宽度</param>
/// <returns>马赛克图像</returns>
public static Image Mosaic(Image imgSrc, int width) {
Bitmap bmp = new Bitmap(imgSrc);
BitmapData bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte[] byColorInfoSrc = new byte[bmpData.Height * bmpData.Stride];
Marshal.Copy(bmpData.Scan0, byColorInfoSrc, 0, byColorInfoSrc.Length);
int indexB = 0;//指定宽度正方形内的 r,g,b 的总和
int indexG = 0;
int indexR = 0;
int rCount = 0;//像素点个数
for (int x = 0, lenx = bmp.Width; x < lenx; x += width) {
for (int y = 0, leny = bmp.Height; y < leny; y += width) {
int r = 0, g = 0, b = 0; rCount = 0;
for (int tempx = x, lentx = x + width <= lenx ? x + width : lenx; tempx < lentx; tempx++) {
for (int tempy = y, lenty = y + width <= leny ? y + width : leny; tempy < lenty; tempy++) {
indexB = tempy * bmpData.Stride + tempx * 3;
indexG = indexB + 1;
indexR = indexB + 2;
b += byColorInfoSrc[indexB];
g += byColorInfoSrc[indexG];
r += byColorInfoSrc[indexR];
rCount++;
}
}//计算rgb总合
for (int tempx = x, lentx = x + width <= lenx ? x + width : lenx; tempx < lentx; tempx++) {
for (int tempy = y, lenty = y + width <= leny ? y + width : leny; tempy < lenty; tempy++) {
indexB = tempy * bmpData.Stride + tempx * 3;
indexG = indexB + 1;
indexR = indexB + 2;
byColorInfoSrc[indexB] = (byte)(b / (rCount));
byColorInfoSrc[indexG] = (byte)(g / (rCount));
byColorInfoSrc[indexR] = (byte)(r / (rCount));
}
}//设置像素为平均值
}
}
Marshal.Copy(byColorInfoSrc, 0, bmpData.Scan0, byColorInfoSrc.Length);
bmp.UnlockBits(bmpData);
return bmp;
}
我在虚拟机里面 马赛克宽度 设置为 100 获取全屏图像处理 也不到 100 毫秒 1600 * 900 分辨率