2011-04-24 43 views
3

這一個後:如何獲得BitmapImage的字節應用<Image.Effect>

BitmapSource originalImage; 
byte[] _originalPixels; 
_originalPixels = new byte[(int) originalImage.Width*(int) originalImage.Height*4]; 
originalImage.CopyPixels(_originalPixels, 4*(int) originalImage.Width, 0); 

副本應用過濾器並沒有什麼奇怪之前的圖像字節。

如何獲得已應用效果的字節?

如何將着色器效果以編程方式應用於byte []或某種低級像素結構數組?

回答

2

如何將圖像渲染到RenderTargetBitmap並使用CopyPixelsRenderTargetBitmap上獲取像素?它有幫助嗎?

+0

THX,用於提示理念 – 2011-04-24 12:15:52

3

助手:

public static class ImageRenderingHelper 
    { 
     public static BitmapSource RenderToBitmap(FrameworkElement target) 
     { 
      int actualWidth = (int)target.ActualWidth; 
      int actualHeight = (int)target.ActualHeight; 

     Rect boundary = VisualTreeHelper.GetDescendantBounds(target); 
     RenderTargetBitmap renderBitmap = new RenderTargetBitmap(actualWidth, actualHeight, 96, 96, PixelFormats.Pbgra32); 

     DrawingVisual drawingVisual = new DrawingVisual(); 
     using (DrawingContext context = drawingVisual.RenderOpen()) 
     { 
      VisualBrush visualBrush = new VisualBrush(target); 
      context.DrawRectangle(visualBrush, null, new Rect(new Point(), boundary.Size)); 
     } 

     renderBitmap.Render(drawingVisual); 
     return renderBitmap; 
    } 

    private static void Arrange(UIElement element, int width, int height) 
    { 
     element.Measure(new Size(width, height)); 
     element.Arrange(new Rect(0, 0, width, height)); 
     element.UpdateLayout(); 
    } 

    public static byte[] RenderImageWithEffects(ImageSource image, IEnumerable<ShaderEffect> effects) 
    { 
     effects = effects.Reverse(); 
     Grid root = new Grid(); 
     Arrange(root, (int)image.Width, (int)image.Height); 
     Grid current = root; 
     foreach (var shaderEffect in effects) 
     { 
      var effect = new Grid(); 
      Arrange(effect, (int)image.Width, (int)image.Height); 
      effect.Effect = shaderEffect; 
      current.Children.Add(effect); 
      current = effect; 
     } 

     Image img = new Image(); 
     img.Source = image; 
     Arrange(img, (int)image.Width, (int)image.Height); 
     current.Children.Add(img); 
     BitmapSource bs = RenderToBitmap(root); 
     byte[] buffer = new byte[(int)bs.Width * (int)bs.Height * 4]; 
     bs.CopyPixels(buffer, 4 * (int)bs.Width, 0); 
     return buffer; 
    } 

    public static byte[] RenderImageWithEffects(string imagePath, IEnumerable<ShaderEffect> effects) 
    { 
     BitmapImage bmp = new BitmapImage(new Uri(imagePath, UriKind.Absolute)); 
     return RenderImageWithEffects(bmp, effects); 
    } 
}