通過一個圖片的URL得到該圖片的尺寸大小(C#)

2010-08-28 10:50:18來源:西部e網(wǎng)作者:

因為在獲取網(wǎng)絡(luò)上的圖片大小或數(shù)據(jù)時,如果不斷地形成臨時文件,再打開,這個過程不僅速度比較慢,而且給人的感覺總有些不爽,當然不失一種解決辦法。一般的期望就是在內(nèi)存中完成所有操作,幸好我們可出使用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。

關(guān)鍵詞:C#