问题
I'm trying to do a super simple thing : get the size of an image.
So I create my BitmapImage
but I'm getting 0 when I try to access the PixelWidth
and PixelHeight
.
How can I accomplish that please?
EDIT: (added sample code)
I'm just doing:
var baseUri = new Uri("ms-appx:///");
var bitmapImage = new BitmapImage(new Uri(baseUri, "Assets/Logo.png"));
MyImage.Source = bitmapImage;
Debug.WriteLine("Width: " + bitmapImage.PixelWidth + " Height: " + bitmapImage.PixelHeight);
In the console, I get:
Width: 0 Height: 0
回答1:
When you want to use the image properties after setting the source for your BitmapImage, you normally have to write an event handler that will execute on ImageOpened.
Also remember that ImageOpened
only fires if the image is downloaded and decoded (i.e. using Image.Source).
var bitmapImage = new BitmapImage(uri);
bitmapImage.ImageOpened += (sender, e) =>
{
Debug.WriteLine("Width: {0}, Height: {1}",
bitmapImage.PixelWidth, bitmapImage.PixelHeight);
};
image.Source = bitmapImage;
回答2:
You can try to initialyze it in a different way. Try this:
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\pics\Water_Lilies.jpg");
myBitmapImage.EndInit();
int w = myBitmapImage.PixelWidth;
来源:https://stackoverflow.com/questions/15406315/bitmapimage-returns-0-for-pixelwidth-and-pixelheight