■ UIElement 클래스를 사용해 JPEG 이미지를 구하는 방법을 보여준다.
▶ 예제 코드 (C#)
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 |
using System.IO; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; #region JPEG 이미지 구하기 - GetJPEGImage(uiElement, scale, qualityLevel) /// <summary> /// JPEG 이미지 구하기 /// </summary> /// <param name="uiElement">UIElement</param> /// <param name="scale">확대/축소 비율</param> /// <param name="qualityLevel">품질 레벨</param> /// <returns>이미지 바이트 배열</returns> public byte[] GetJPEGImage(UIElement uiElement, double scale, int qualityLevel) { double actualWidth = uiElement.RenderSize.Width; double actualHeight = uiElement.RenderSize.Height; double renderWidth = actualWidth * scale; double renderHeight = actualHeight * scale; RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); VisualBrush visualBrush = new VisualBrush(uiElement); DrawingVisual drawingVisual = new DrawingVisual(); using(DrawingContext drawingContext = drawingVisual.RenderOpen()) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTargetBitmap.Render(drawingVisual); JpegBitmapEncoder jpegBitmapEncoder = new JpegBitmapEncoder(); jpegBitmapEncoder.QualityLevel = qualityLevel; jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); byte[] imageByteArray; using(MemoryStream memoryStream = new MemoryStream()) { jpegBitmapEncoder.Save(memoryStream); imageByteArray = memoryStream.ToArray(); } return imageByteArray; } |