0
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
| | using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace MaskTest {
class Program {
static void Main(string[] args) {
foreach (string file in Directory.GetFiles(".", "*.bmp")) {
Bitmap srcBmp = (Bitmap)Bitmap.FromFile(file);
Bitmap tmpBmp = new Bitmap(srcBmp.Width, srcBmp.Height, PixelFormat.Format32bppArgb);
Graphics tmpG = Graphics.FromImage(tmpBmp);
tmpG.DrawImage(srcBmp, new Rectangle(0, 0, tmpBmp.Width, tmpBmp.Height),
new Rectangle(0, 0, srcBmp.Width, srcBmp.Height), GraphicsUnit.Pixel);
Bitmap dstBmp = new Bitmap(srcBmp.Width / 2, srcBmp.Height, PixelFormat.Format32bppArgb);
Graphics dstG = Graphics.FromImage(dstBmp);
dstG.DrawImage(srcBmp, new Rectangle(0, 0, dstBmp.Width, dstBmp.Height),
0, 0, srcBmp.Width / 2, srcBmp.Height, GraphicsUnit.Pixel);
Bitmap mskBmp = new Bitmap(srcBmp.Width / 2, srcBmp.Height, PixelFormat.Format32bppArgb);
Graphics mskG = Graphics.FromImage(mskBmp);
mskG.DrawImage(srcBmp, new Rectangle(0, 0, dstBmp.Width, dstBmp.Height),
srcBmp.Width/2 , 0, srcBmp.Width / 2, srcBmp.Height, GraphicsUnit.Pixel);
Mask(dstBmp, mskBmp,true);
dstBmp.Save(file.ToLower().Replace(".bmp", ".png"), ImageFormat.Png);
}
}
public unsafe static void Mask(Bitmap srcBmp,Bitmap mskBmp,bool isNegate){
int w = srcBmp.Width;
int h = srcBmp.Height;
if (mskBmp.Width != w || mskBmp.Height != h) {
throw new ArgumentException("bitmap size unmatch");
}
if (srcBmp.PixelFormat != PixelFormat.Format32bppArgb ||
mskBmp.PixelFormat != PixelFormat.Format32bppArgb) {
throw new ArgumentException("bitmap must be 32bpp");
}
BitmapData srcData = srcBmp.LockBits(new Rectangle(0, 0, w, h),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
BitmapData mskData = mskBmp.LockBits(new Rectangle(0, 0, w, h),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte* pSrcBase = (byte*)srcData.Scan0.ToPointer();
byte* pMskBase = (byte*)mskData.Scan0.ToPointer();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
byte* pSrc = pSrcBase + (y * w + x) * 4;
byte* pMsk = pMskBase + (y * w + x) * 4;
int rgbsum = (*(pMsk + 0) + *(pMsk + 1) + *(pMsk + 2))/3;
if (isNegate) {
rgbsum = 255 - rgbsum;
}
*(pSrc + 3) = (byte)rgbsum;
}
}
srcBmp.UnlockBits(srcData);
mskBmp.UnlockBits(mskData);
}
}
}
|