개발일기/C#

[C#] Bitmap객체를 이용한 이미지 분할

쌀덕이 2014. 1. 13. 17:26

이전에 작업을 하던 도중.. 이미지를 여러개로 분할하여 가지고 있어야 했는데..


Graphics객체로는 분할하여 출력은 가능하지만.. 저장은 파일로 내리는 것이 대부분이라..


Bitmap객체의 SetPixel과 GetPixel로 이미지를 가로로 분할해주는 소스를 작성해보았다.



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
/// <summary>
        /// 비트맵의 전체 픽셀을 Color Array로 반환한다.
        /// </summary>
        private Color[,] GetBitmapPixel(Bitmap bitmap)
        {
            if (bitmap == null)
                return null;
 
            Color[,] pixel = new Color[bitmap.Width, bitmap.Height];
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    pixel[i, j] = bitmap.GetPixel(i, j);
                }
            }
            return pixel;
        }
 
        /// <summary>
        /// 입력받은 Color Array에서 지정된 넓이, 높이, 위치 만큼 가로로 분할하여 비트맵을 반환한다.
        /// </summary>
        private Bitmap GetDivisionBitmap(Color[,] pixel, int width, int height, int position)
        {
            Bitmap bitmap = new Bitmap(width, height);
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int left = x + width * position;
                    bitmap.SetPixel(x, y, pixel[left, y]);
                }
            }
            return bitmap;
        }


간단하게 소스는 비트맵 객체를 GetPixel을 이용해 메트릭스에 저장한 후..


넓이와 높이 위치를 지정하면 새로운 Bitmap객체에 SetPixel로 값을 복사하는 방식이다..


예전에 작성한 소스지만 이젠 하나씩 정리해가면서 업로드해야겠다..