开发者

How to get BitmapImage bytes after applying <Image.Effect>

This one:

BitmapSource originalImage;
byte[] _originalPixels;
_originalPixels = new byte[(int) originalImage.Width*(int) originalImage.Height*4];
originalImage.CopyPixels(_origina开发者_JAVA百科lPixels, 4*(int) originalImage.Width, 0);

copies the image bytes before applying a filter and there is no surprising.

How to get bytes with an effect already applied?

How to apply shader effect programmatically to byte[] or some kind low level pixel structure array?


Helper:

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);
    }
}


How about rendering your image to a RenderTargetBitmap and getting the pixels using CopyPixels on the RenderTargetBitmap? Does it help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜