下载图片的大小?

时间:2014-12-29 16:43:04

标签: c# windows-runtime

我尝试获取下载图像的宽高比。为此我需要高度和宽度,但每次尝试我都会得到0.0或NaN。我试过Image和BitmapImage。我试图设置Stretch,其中一个尺寸希望另一个尺寸会自动填充。

他们两个都没有我能读的设定尺寸:

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

BitmapImage bitmap = new BitmapImage(new Uri(customItem.FullURL));

4 个答案:

答案 0 :(得分:0)

您可以按照this answer中的建议尝试使用WebClient。

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

答案 1 :(得分:0)

试试这个(只需用你的url字符串替换我的url字符串):

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

答案 2 :(得分:0)

这段代码可能会对您有所帮助:

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

答案 3 :(得分:0)

图像尺寸在打开之前无法使用。在ImageOpened事件处理程序中测试宽度和高度。

<强>代码

  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;