通过一个图片的URL得到该图片的尺寸大小(C#)

2010-08-28 10:50:18来源:西部e网作者:

因为在获取网络上的图片大小或数据时,如果不断地形成临时文件,再打开,这个过程不仅速度比较慢,而且给人的感觉总有些不爽,当然不失一种解决办法。一般的期望就是在内存中完成所有操作,幸好我们可出使用MemoryStream,通过它我们可以比较轻松地达到目的。

    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.textBox1.Text);
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        byte[] buffer = new byte[1024];

        if (!response.ContentType.ToLower().StartsWith("text/"))
        {
            try
            {
                Stream outStream = new MemoryStream();
                Stream inStream = response.GetResponseStream();

                int bufferLength;
                do
                {
                    bufferLength = inStream.Read(buffer, 0, buffer.Length);
                    if (bufferLength > 0)
                        outStream.Write(buffer, 0, bufferLength);
                }
                while (bufferLength > 0);

                outStream.Flush();
                outStream.Seek(0, SeekOrigin.Begin);
                inStream.Close();

                Image image = Image.FromStream(outStream);
                outStream.Close();
                MessageBox.Show("image   :=" + image.Width + "X" + image.Height);
                image.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("非图像格式\r\n" + ex.Message);
            }
        }
        else
        {
            MessageBox.Show("非图像格式");
        }
    }

this.textBox1.Text存储的是URL。

关键词:C#