分享一个图片毛玻璃效果的算法
原理:
从原像素的某个范围内随机选取一部分像素,讲其进行Alpha混合模糊得到目标像素值
下面上代码:
原理:
从原像素的某个范围内随机选取一部分像素,讲其进行Alpha混合模糊得到目标像素值
下面上代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
/// <summary>
/// 对颜色数组进行混合
/// </summary>
/// <param name="colors"></param>
/// <returns></returns>
public
static
Color BlendColor(Color[] colors)
{
if
(colors.Length <= 0)
return
Color.Transparent;
ulong
asum = 0, rsum = 0, gsum = 0, bsum = 0;
for
(
int
i = 0, len = colors.Length; i < len; i++)
{
asum += colors[i].A;
rsum += (
ulong
)(colors[i].A*colors[i].R);
gsum += (
ulong
)(colors[i].G*colors[i].A);
bsum += (
ulong
)(colors[i].B*colors[i].A);
}
if
(asum == 0)
return
Color.Transparent;
rsum /= asum;
gsum /= asum;
bsum /= asum;
asum /= (
ulong
)colors.Length;
return
Color.FromArgb((
int
)asum, (
int
)rsum, (
int
)gsum, (
int
)bsum);
}
/// <summary>
/// 毛玻璃效果
/// </summary>
/// <param name="srcBmp">源图片</param>
/// <param name="minRadius">最小离散半径</param>
/// <param name="maxRadius">最大离散半径</param>
/// <param name="samples">采样点数</param>
/// <returns></returns>
public
static
Bitmap FrostedEffect(Bitmap srcBmp,
int
minRadius,
int
maxRadius,
int
samples)
{
int
width = srcBmp.Width;
int
height = srcBmp.Height;
Bitmap targBmp =
new
Bitmap(width, height, srcBmp.PixelFormat);
BitmapData srcData = srcBmp.LockBits(
new
Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, srcBmp.PixelFormat);
BitmapData targData = targBmp.LockBits(
new
Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, targBmp.PixelFormat);
int
pxsize = Image.GetPixelFormatSize(srcBmp.PixelFormat) / 8;
//像素大小
bool
bAlpha = Image.IsAlphaPixelFormat(srcBmp.PixelFormat);
int
offset = srcData.Stride - srcData.Width * pxsize;
Random rand =
new
Random();
Color[] sampleColors =
new
Color[samples];
unsafe
{
byte
* srcptr = (
byte
*)srcData.Scan0;
for
(
int
i = 0; i < height; i++)
{
for
(
int
j = 0; j < width; j++)
{
for
(
int
s = 0; s < samples; s++)
{
double
d = rand.Next(minRadius, maxRadius);
double
angle = rand.NextDouble() * Math.PI * 2;
double
p = Math.Sin(angle);
int
samh = (
int
)(i + Math.Sin(angle) * d);
int
samw = (
int
)(j + Math.Cos(angle) * d);
samh = samh < 0 ? 0 : samh > height - 1 ? height - 1 : samh;
samw = samw < 0 ? 0 : samw > width ? width : samw;
byte
* ptr = srcptr + samh * srcData.Stride + samw * pxsize;
if
(bAlpha)
sampleColors[s] = Color.FromArgb(*(ptr + 3), *(ptr + 2), *(ptr + 1), *ptr);
else
sampleColors[s] = Color.FromArgb(*(ptr + 2), *(ptr + 1), *ptr);
}
Color col = BlendColor(sampleColors);
byte
* targptr = (
byte
*)targData.Scan0 + srcData.Stride * i + j*pxsize;
*targptr = col.B;
*(targptr + 1) = col.G;
*(targptr + 2) = col.R;
if
(bAlpha)
*(targptr + 3) = col.A;
}
}
}
srcBmp.UnlockBits(srcData);
targBmp.UnlockBits(targData);
return
targBmp;
}
给个效果图
|