Show / Hide Table of Contents

Практическое руководство. Кодирование визуального элемента в файл изображения

В этом примере показаны способы кодирования Visual объекта в файл изображения с помощью RenderTargetBitmap и PngBitmapEncoder.

Пример

DrawingVisual Создается с помощью BitmapImage и FormattedText который отображается RenderTargetBitmap. Визуализированный точечный рисунок затем используется для создания BitmapFrame добавляемым к PngBitmapEncoder для создания нового Формат PNG (Portable Network Graphics) файл.

// Base Image
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("sampleImages/waterlilies.jpg",UriKind.Relative);
bi.DecodePixelWidth = 200;
bi.EndInit();

// Text to render on the image.
FormattedText text = new FormattedText("Waterlilies",
        new CultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
        this.FontSize,
        Brushes.White);

// The Visual to use as the source of the RenderTargetBitmap.
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(bi,new Rect(0,0,bi.Width,bi.Height));
drawingContext.DrawText(text, new Point(bi.Height/2, 0));
drawingContext.Close();

// The BitmapSource that is rendered with a Visual.
RenderTargetBitmap rtb = new RenderTargetBitmap(bi.PixelWidth, bi.PixelHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(drawingVisual);

// Encoding the RenderBitmapTarget as a PNG file.
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
using (Stream stm = File.Create("new.png"))
{
   png.Save(stm);
}

Объект PngBitmapEncoder использовался в этом примере, но содержит производного BitmapEncoder объекты можно было бы для создания файла образа.

См. также

  • DrawingContext
  • Общие сведения об обработке изображений
  • Обзор объектов Drawing
  • Использование объектов DrawingVisual
Back to top Неофициальная документация по .NET на русском языке. Лицензия: CC-BY 4.0. Основано на документации по .NET с Microsoft Docs
Generated by DocFX