[WPF] Image 붙이기

C#/WPF 2020. 7. 27. 12:18
728x90
728x170

아래 예시는 각기 다른 4가지 이미지를 4분면에 그리는 코드입니다.

 

4분면에 이미지를 하나씩 그리는 예시입니다.

처음 이미지의 크기에 따라 나머지 이미지 들도 크기가 지정되며

바둑판모양으로 이미지가 달라 붙습니다.

 

        private void MergeImage(string path1, string path2, string path3, string path4, string outputFilePath)

        {

            // 이미지를 로드합니다.

            BitmapFrame frame1 = BitmapDecoder.Create(new Uri(path1), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

            BitmapFrame frame2 = BitmapDecoder.Create(new Uri(path2), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

            BitmapFrame frame3 = BitmapDecoder.Create(new Uri(path3), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

            BitmapFrame frame4 = BitmapDecoder.Create(new Uri(path4), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

 

            // 첫번째이미지 기준으로 그려질 이미지의 크기를 정의합니다.

            int imageWidth = frame1.PixelWidth;

            int imageHeight = frame1.PixelHeight;

 

            // DrawingVisual 에 전체 4분면에서 각 분면 이미지를 그립니다.

            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())

            {

                drawingContext.DrawImage(frame1, new Rect(0, 0, imageWidth, imageHeight));

                drawingContext.DrawImage(frame2, new Rect(imageWidth, 0, imageWidth, imageHeight));

                drawingContext.DrawImage(frame3, new Rect(0, imageHeight, imageWidth, imageHeight));

                drawingContext.DrawImage(frame4, new Rect(imageWidth, imageHeight, imageWidth, imageHeight));

            }

 

            // RenderTargetBitmap 을 사용해 DrawingVisual 을 BitmapSource 객체로 변환합니다.

            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(imageWidth * 2, imageHeight * 2, 96, 96, PixelFormats.Pbgra32);

            renderTargetBitmap.Render(drawingVisual);

 

            // BitmapSource 를 PngBitmapEncoder 를 사용해 frame 에 추가합니다.

            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

 

            // 이미지를 저장합니다.

            using (Stream stream = File.Create(outputFilePath))

            {

                encoder.Save(stream);

            }

        }

 

* ico 파일 지정도 가능

 

결과

728x90
그리드형
Posted by kjun
,