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

本文关键字:图像 获取 同步 UWP 应用程序 | 更新日期: 2023-09-27 18:12:01

我试图在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并返回一个包含维度的点。即。public Point getImageDimensions(Uri u){…}

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

如果需要,我可以提供更多的细节,提前感谢。

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

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

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

我试图得到图像的尺寸之前,我在OnLoaded()方法中显示它。我想要同步(而不是异步)执行此操作,因为我需要在程序继续之前知道图像的尺寸。

在构造函数中调用async函数会遇到一些问题,详细信息可以参考Stephen Cleary的博客:async OOP 2: Constructors.

在UWP中,您可以将页面初始化代码(getImageDimensions和显示图像的代码)放在Page中。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;
    ...
}

更新:

你能推荐一种更简单、同步的方法来获取尺寸吗?

大多数与文件相关的操作都被设计为异步操作,用户可以使用/不使用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;

与其将其流化为位图,不如将其加载到System.Drawing中。像这样?:

System.Drawing.Image img = System.Drawing.Image.FromStream(myStream);

然后您可以访问System.Drawing。图像的大小属性,它应该给你你需要的,以及方便地访问调整大小。如果内存可用,所有这些都可以在。net Core和UWP中使用。