0

I try to get aspect ratio of downloaded images. For this purpose I need height and width, but everytime and everyway I try, I get only 0.0 or NaN. I tried Image and BitmapImage. I tried to set Stretch, one of the sizes in hope the other one will be filled automatically.

Both of them don't have set sizes I can read:

Image image = new Image();
image.Source = new BitmapImage(new Uri(customItem.FullURL, UriKind.Absolute));

BitmapImage bitmap = new BitmapImage(new Uri(customItem.FullURL));
Qerts
  • 935
  • 1
  • 15
  • 29

4 Answers4

0

You can try using the WebClient as suggested in this answer.

using System.Drawing;
using System.Net;
using System.IO;
using System.Windows.Forms;

WebClient wc = new WebClient();                
using (MemoryStream ms = new MemoryStream(wc.DownloadData(customItem.FullURL))) {
    Image img = Image.FromStream(ms);
    MessageBox.Show(img.Height.ToString() + " -- " + img.Width.ToString());
}
Community
  • 1
  • 1
jiverson
  • 1,206
  • 12
  • 25
0

Try this (Just replace my url string with your url string):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Net;
namespace GDI
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            Bitmap bmp = new Bitmap(wc.OpenRead("https://s0.2mdn.net/viewad/3092927/Freedom_AW_D_Zenith_119053_DS_Apple_Pay_Bleachers_300x250.jpg"));
            Console.WriteLine("Width=" + bmp.Width.ToString() + ", Height=" + bmp.Height.ToString());
            Console.ReadLine();
        }
    }
}
David P
  • 2,027
  • 3
  • 15
  • 27
  • I am afraid this code is obsolete for me. For something like this I have to use HttpClient and asnyc/await operations, but I am going to try this approach. – Qerts Dec 29 '14 at 19:59
0

May be this code will helpful for you:

Image image = System.Drawing.Image.FromFile("\1.jpg"); Console.Write("Width: " + image.Width + ", Height: " + image.Height);

netwer
  • 737
  • 11
  • 33
0

The size of the image is not available until it is open. Test for width and height in the ImageOpened event handler.

Code

  var bitmap = new BitmapImage(new Uri(uri));

  // ImageOpened fires when image is downloaded and decoded
  bitmap.ImageOpened += (s, args) =>
  {
    var w = bitmap.PixelWidth;
  };

  // setting the source causes the ImageOpened or ImageFailed event to fire.
  // image2 must be in visual tree

  image2.Source = bitmap;
Walt Ritscher
  • 6,977
  • 1
  • 28
  • 35
  • This is quite blind ended situation. I need to get image size in TemplateSelector before visualizing the image. Only thing I can think of is to create new Page for visualizing this image for purposes of TemplateSelector. But this solution seems to me very inelegant and slow. – Qerts Dec 30 '14 at 09:54