開発用メモ

System.Drawing.Imaging.ColorMatrixを使う

参考ブログ

グレースケール変換(英語)

Everything is expanded.Everything is shortened.
  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
 
 
 
 
 
-
-
|
|
|
|
!
-
|
|
|
|
!
|
-
|
-
|
|
|
!
|
|
!
|
-
|
!
|
-
|
-
|
-
|
|
|
!
!
|
!
!
!
 using System;
 using System.Drawing;
 using System.Drawing.Imaging;
 
    public class PictureUtil
    {
        static readonly float[][] mtrxGrayScale = new float[][]{
                new float[]{0.3f,0.3f,0.3f,0,0},
                new float[]{0.59f,0.59f,0.59f,0,0},
                new float[]{0.11f,0.11f,0.11f,0,0},
                new float[]{0,0,0,1,0},
                new float[]{0,0,0,0,1} };
        static readonly float[][] mtrxWork = new float[][]{
                new float[]{0,0,0,0,0},
                new float[]{0,0,0,0,0},
                new float[]{0,0,0,0,0},
                new float[]{0,0,0,1,0},
                new float[]{0,0,0,0,1} };
 
        public static Bitmap createGrayScale(Image orig, float bright, float contrast){
            float[][] mtrx = mtrxWork;
            for(int i=0; i<3; i++) {
                for(int j=0; j<3; j++)
                    mtrx[i][j]=mtrxGrayScale[i][j]*contrast;
                mtrx[3][i]=bright;
            }
            float[][] mtrx2 = mtrxGrayScale;
            return createMatrixImage(orig,mtrx);
        }    
 
        public static Bitmap createGrayScale(Image orig){
            return createMatrixImage(orig,mtrxGrayScale);
        }    
 
        private static Bitmap createMatrixImage(Image orig, float[][] matrix){
            Bitmap img = new Bitmap(orig.Width,orig.Height);
            using(Graphics g = Graphics.FromImage(img)){
                ColorMatrix cmGray = new ColorMatrix(matrix);
                using (ImageAttributes ia = new ImageAttributes()){
                    ia.SetColorMatrix( cmGray, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                    Rectangle r = new Rectangle(0,0,orig.Width,orig.Height);
                    g.DrawImage(orig, r,0,0,r.Width,r.Height,GraphicsUnit.Pixel, ia);
                }
            }
            return img;
        }    
    }
 }

Last-modified: 2008-05-17 (土) 16:52:11 (937d)