如何在UWP应用程序中同步获取图像的尺寸?

Ang*_*ino 2 .net c# windows windows-10 windows-10-universal

我想在OnLoaded()方法中显示图像之前获取图像的尺寸.我想同步(不是异步)这样做,因为我需要在程序继续之前知道图像的尺寸.我正在制作一个映射程序,其中背景图像的坐标,比例和平移偏移很重要,并且都取决于从应用程序的最开始就知道图像的尺寸.

我已经阅读了大部分有关StorageFile,SoftwareBitmap和异步方法调用的msdn文档,并尝试了许多我在网上找到的方法,但没有成功. https://msdn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps

https://msdn.microsoft.com/en-us/windows/uwp/threading-async/call-asynchronous-apis-in-csharp-or-visual-basic

基本上我正在寻找一个同步c#函数,它接受一个图像文件的uri并返回一个包含维度的Point.即公共点getImageDimensions(Uri u){...}

这个功能很容易在Android应用程序中实现,我不明白为什么它在UWP应用程序中如此困难.

如果需要,我可以提供更多详细信息,提前感谢.

我用以下代码得到以下错误:
抛出异常:在App1.exe中
抛出'System.Exception' 异常抛出:mscorlib.ni.dll中的'System.AggregateException'

App1.xaml.cs

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Shapes;

namespace App1
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += OnLoaded;

            Point p = Task.Run(() => getImageDimensions("ms-appx:///Assets/NewSpaceBackground.png")).Result;
            Debug.WriteLine("p.X: " + p.X + " p.Y: " + p.Y);
        }

        void OnLoaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            Rectangle backgroundRect1 = new Rectangle();
            ImageBrush imgBrushBackground1 = new ImageBrush();
            imgBrushBackground1.ImageSource = new BitmapImage(new Uri(@"ms-appx:///Assets/NewSpaceBackground.png"));
            backgroundRect1.Fill = imgBrushBackground1;
            //backgroundMap.Add(backgroundRect1);
        }

        public async Task<Point> getImageDimensions(string strURI)
        {
            Point p;
            StorageFile photo;
            try
            {
                var uri = new Uri(strURI);
                photo = await StorageFile.GetFileFromApplicationUriAsync(uri);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.StackTrace);
                return p;
            }
            //read in the bitmap stream
            IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read);
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
            SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

            //convert the image to a bitmap
            SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
            await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);

            //print out the dimensions
            Debug.WriteLine(softwareBitmapBGR8.PixelWidth + " " + softwareBitmapBGR8.PixelHeight);
            p.X = softwareBitmapBGR8.PixelWidth;
            p.Y = softwareBitmapBGR8.PixelHeight;

            return p;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Elv*_*SFT 7

我想在OnLoaded()方法中显示图像之前获取图像的尺寸.我想同步(不是异步)这样做,因为我需要在程序继续之前知道图像的尺寸.

当您想在构造函数中调用异步函数时会出现一些问题,有关详细信息,请参阅Stephen Cleary的博客:Async OOP 2:Constructors.

在UWP中,您可以getImageDimensionsPage.OnNavigatedTo方法中放置页面初始化代码(以及显示图像的代码)并await在其中使用:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    Point p = await getImageDimensions("ms-appx:///Assets/NewSpaceBackground.png");
    Debug.WriteLine("p.X: " + p.X + " p.Y: " + p.Y);

    Rectangle backgroundRect1 = new Rectangle();
    ImageBrush imgBrushBackground1 = new ImageBrush();
    imgBrushBackground1.ImageSource = new BitmapImage(new Uri(@"ms-appx:///Images/image03.jpg"));
    backgroundRect1.Fill = imgBrushBackground1;
    ...
}
Run Code Online (Sandbox Code Playgroud)

更新:

您会建议使用更简单,同步的方式来获取尺寸吗?

大多数与文件相关的操作都设计为异步,用户可以使用/不使用await选择同步或异步操作.

确实有一种简单的方法来获得图像的维度:

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///images/image01.png"));
var properties=await file.Properties.GetImagePropertiesAsync();
var width = properties.Width;
var height = properties.Height;
Run Code Online (Sandbox Code Playgroud)