.NETにおける画像処理を解説する
ビットマップと描画
Graphicsオブジェクトで描画することができる。一例を示す。
Graphics g = Graphics.FromImage(dest); g.DrawImage(src, 0, 0); g.Dispose();描画元と描画先の座標を指定することも可能である。例を示す。
Graphics g = Graphics.FromImage(dest); Rectangle destRect = new Rectangle(m_aWidth*x, m_aHeight*y, m_aWidth, m_aHeight); g.DrawImage(bmp, destRect, 0, 0, m_aWidth, m_aHeight, GraphicsUnit.Pixel); g.Dispose();クリップボードの画像形式はPixelFormat.Format32bppRgbである。32ビット形式で赤、緑、青に8ビット割り当てられ、のこり8ビットは未使用である。次のコードでクリップボードの画像形式を確認できる。
Bitmap clipSrc = (Bitmap)Clipboard.GetImage(); MessageBox.Show("" + clipSrc.PixelFormat);これでクリップボードが画像のときには、メッセージボックスで画像形式が表示される。
これを未使用部分にアルファを割り当てたFormat32bppArgb形式に変換する方法としては、Cloneメソッドを使用する方法がある。
Bitmap clipSrc = (Bitmap)Clipboard.GetImage(); Rectangle r = new Rectangle(0, 0, clipSrc.Width, clipSrc.Height); Bitmap clip = clipSrc.Clone(r, System.Drawing.Imaging.PixelFormat.Format32bppArgb);これでアルファを割り当てることができる。割り当てる一例を示す。
for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = clip.GetPixel(j, i); Color tc = Color.FromArgb(128, c); clip.SetPixel(j, i, tc); } }アルファは0で完全な透明、255で完全な不透明である。
アルファ値を割り当てる一例を示す。先ほどのclipに対して変更を行う。
for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = clip.GetPixel(j, i); Color tc = Color.FromArgb(128, c); clip.SetPixel(j, i, tc); } }C#において、この方法は処理に非常に時間がかかる。
描画処理においては不透明度をもちいて描画指定するオプションがある。ColorMatrixを設定したImageAttributesをDrawImageの引数に渡すのである。
float opacity = 0.5F; System.Drawing.Imaging.ColorMatrix cm = new System.Drawing.Imaging.ColorMatrix(); cm.Matrix00 = 1; cm.Matrix11 = 1; cm.Matrix22 = 1; cm.Matrix33 = opacity; cm.Matrix44 = 1; System.Drawing.Imaging.ImageAttributes ia = new System.Drawing.Imaging.ImageAttributes(); ia.SetColorMatrix(cm);cm.Matrix33が0から1までの値で不透明度を指定する。0が完全な透明で、1が完全な不透明である。ia変数をDrawImageメソッドの引数に渡す。