2015-12-17 3 views
1

im, пытающийся преобразовать холст в источник изображения для использования в качестве OpacityMask, я хочу сохранить его в памяти, а не сохранять его как файл, но у меня проблемы. Ниже мой код, я думаю, что я ошибаюсь!Convert Canvas to ImageSource

Действительно, мне нужно получить информацию об изображении как Base64String, поэтому где-то между этим мне нужно преобразовать RenderTargetBitmap!

public BitmapSource ExportToPng(Uri path, Canvas surface) 
{ 
    BitmapEncoder encoder = new PngBitmapEncoder(); 
    System.IO.MemoryStream myStream = new System.IO.MemoryStream(); 

    // Save current canvas transform 
    Transform transform = surface.LayoutTransform; 
    // reset current transform (in case it is scaled or rotated) 
    surface.LayoutTransform = null; 

    // Get the size of canvas 
    System.Windows.Size size = new System.Windows.Size(surface.ActualWidth, surface.ActualHeight); 
    // Measure and arrange the surface 
    // VERY IMPORTANT 
    surface.Measure(size); 
    surface.Arrange(new Rect(size)); 

    // Create a render bitmap and push the surface to it 
    RenderTargetBitmap renderBitmap = 
     new RenderTargetBitmap(
     (int)size.Width, 
     (int)size.Height, 
     96d, 
     96d, 
     PixelFormats.Pbgra32); 
    renderBitmap.Render(surface); 

    // push the rendered bitmap to it 
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); 
    // save the data to the stream 
    encoder.Save(myStream); 

    // Restore previously saved layout 
    surface.LayoutTransform = transform; 

    var sr = new System.IO.StreamReader(myStream); 
    var myStr = sr.ReadToEnd(); 
    var bytes = Convert.FromBase64String(myStr); 

    // Save to memory 
    /*Bitmap pg = new Bitmap("525, 350"); 
    Graphics gr = Graphics.FromImage(pg); 

    gr.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 255, 255)), 0, 0, (float)size.Width, (float)size.Height); 
    gr.DrawImage(System.Drawing.Bitmap.FromStream(myStream), 0, 0);*/ 



    return BitmapFromBase64(myStr); 
} 
public static BitmapSource BitmapFromBase64(string base64String) 
{ 
    var bytes = Convert.FromBase64String(base64String); 

    using (var stream = new System.IO.MemoryStream(bytes)) 
    { 
     return BitmapFrame.Create(stream, 
      BitmapCreateOptions.None, BitmapCacheOption.OnLoad); 
    } 
} 

Edit:

Просто найти другой возможный путь, однако это создает DrawingVisual, мне нужно, чтобы преобразовать его в ImageBrush

C#

// Create a DrawingVisual that contains a rectangle. 
     private DrawingVisual CreateDrawingVisualRectangle(List<Rectangle> rectangles) 
     { 
      DrawingVisual drawingVisual = new DrawingVisual(); 

      // Retrieve the DrawingContext in order to create new drawing content. 
      DrawingContext drawingContext = drawingVisual.RenderOpen(); 

      // Create a rectangle and draw it in the DrawingContext. 
      foreach(Rectangle x in rectangles) 
      { 
       Rect rect = new Rect(new System.Windows.Point(x.X, x.Y), new System.Windows.Size(x.Width, x.Height)); 
       drawingContext.DrawRectangle(System.Windows.Media.Brushes.Black, (System.Windows.Media.Pen)null, rect); 
      } 

     // Persist the drawing content. 
     drawingContext.Close(); 

     return drawingVisual; 
    } 
+1

UIElement принимает любую кисть как OpacityMask. Почему бы не использовать VisualBrush? Холст c = новый Canvas(); element.OpacityMask = новый VisualBrush (c); – SnowballTwo

+0

А, не думал, что я могу использовать VisualBrush там, спасибо! –

+0

Это делает ВСЕ намного проще, я думал, что мне пришлось преобразовать холст в какую-то форму изображения, но возможность использовать его напрямую МНОГО лучше –

ответ

1

UIElement принимает любой кисть как OpacityMask. Вы можете просто создать VisualBrush из Canvas, так как базовым классом каждого UIElement является SWM.Visual.

Canvas c = new Canvas(); 
element.OpacityMask = new VisualBrush(c); 

С уважением, Snowball