Maximus
Maximus

Reputation: 1299

How to load an Image in memory without the UI (UWP)

I'm trying to open an image in memory and set it's Source property. I can't use the UI for this, it's work I'd like to happen in the background. However, the ImageOpened doesn't fire. Any other ways to achieve this?

var bounds = ApplicationView.GetForCurrentView().VisibleBounds;
var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
var desktopSize = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

var image = new Image()
{
    Width = desktopSize.Width,
    Height = desktopSize.Height,
};

image.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
image.Arrange(new Rect(0, 0, desktopSize.Width, desktopSize.Height));
image.UpdateLayout();

image.Source = new BitmapImage(new Uri(file.Path, UriKind.RelativeOrAbsolute));

image.ImageOpened += (sender, e) =>
{
    // Currently not firing ...
};

My goal would then be to do some work on the Image and save it to a file using theRenderTargetBitmap class.

Upvotes: 0

Views: 1134

Answers (3)

Johnny Westlake
Johnny Westlake

Reputation: 1460

If you're going to be doing image editing / manipulation, you'd be better off using the Win2D library Nuget package from Microsoft, so your code would look something like this:

public static async Task DoImageStuffAsync(Uri sourceUri, StorageFile outputFile)
    {
        using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(CanvasDevice.GetSharedDevice(), sourceUri).AsTask().ConfigureAwait(false))
        using (CanvasRenderTarget target = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi))
        {
            using (var ds = target.CreateDrawingSession())
            {
                // todo : custom drawing code - this just draws the source image
                ds.DrawImage(bitmap);
            }

            using (var outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite).AsTask().ConfigureAwait(false))
            {
                await target.SaveAsync(outputStream, CanvasBitmapFileFormat.JpegXR).AsTask().ConfigureAwait(false);
            }
        }
    }

Upvotes: 1

Jet  Chopper
Jet Chopper

Reputation: 1488

Here's async task you may use:

    private async Task<BitmapImage> CreateBitmapAsync(Uri uri, int decodeWidth, int decodeHeight)
    {
        var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);
        var bitmap = new BitmapImage { DecodePixelWidth = decodeWidth, DecodePixelHeight = decodeHeight };

        using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read))
        {
            await bitmap.SetSourceAsync(fileStream);
        }

        return bitmap;
    }

Also you should subscribe to event before loading source to Image

Upvotes: 2

Wyck
Wyck

Reputation: 11740

Here's a completely standalone, off-screen render-to-file example. You provide an input image filename and output image filename.

It grabs the top 256 x 64 corner of your image and superimposes some ugly "Hello, world!" text over it and saves it to a file.

Example Output

using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

class OffscreenRenderer
{
    public void Render(string sourceImageFilename, string outputImageFilename)
    {
        FontFamily fontFamily = new FontFamily("Arial");
        double fontSize = 42.0;
        Brush foreground = new System.Windows.Media.SolidColorBrush(Color.FromArgb(255, 255, 128, 0));

        FormattedText text = new FormattedText("Hello, world!",
                new CultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                fontSize,
                foreground);

        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        var overlayImage = new BitmapImage(new Uri(sourceImageFilename));
        drawingContext.DrawImage(overlayImage,
                                    new Rect(0, 0, overlayImage.Width, overlayImage.Height));
        drawingContext.DrawText(text, new Point(2, 2));
        drawingContext.Close();

        RenderTargetBitmap rtb = new RenderTargetBitmap(256, 64, 96, 96, PixelFormats.Pbgra32);
        rtb.Render(drawingVisual);

        PngBitmapEncoder png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(rtb));
        using (Stream stream = File.Create(outputImageFilename))
        {
            png.Save(stream);
        }
    }
}

Upvotes: 0

Related Questions