簡體   English   中英

如何在沒有UI(UWP)的情況下將圖像加載到內存中

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

我正在嘗試在內存中打開圖像並將其設置為Source屬性。 我不能為此使用UI,這是我想在后台進行的工作。 但是,ImageOpened不會觸發。 還有其他方法可以做到這一點嗎?

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

然后,我的目標是在Image上做一些工作,並使用RenderTargetBitmap類將其保存到文件中。

您可以使用以下異步任務:

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

另外,在將源加載到Image之前,您應該先訂閱事件

如果您要進行圖像編輯/操作,最好使用Microsoft的Win2D庫Nuget包,因此您的代碼應如下所示:

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

這是一個完全獨立的屏幕外渲染到文件的示例。 您提供輸入圖像文件名和輸出圖像文件名。

它抓住了圖像的頂部256 x 64角,並疊加了一些難看的“你好,世界!” 在其上輸入文本並將其保存到文件中。

示例輸出

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM