December 02, 2011

Show An Image In PictureBox From URL

บทความนี้ จะสอนเกี่ยวกับการนำ URL ของรูปภาพ มาแสดงใน PictureBox ของโปรแกรมเรา หน้าตาของโปรแกรมคร่าวๆ ก็จะประมาณนี้


ประกอบไปด้วย textBox1 สำหรับรับ string URL, button_show สำหรับโหลดรูปภาพ และ pictureBox1 เป็นพื้นที่สำหรับแสดงรูปภาพ
ส่วนหัวของโปรแกรม หรือ namespace ที่จำเป็นต้องใช้ :
using System.Net;
using System.IO;
Method สำหรับดาวน์โหลดรูปภาพ :
static public byte[] DownloadData(string url)
{
   HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
   WebResponse myResp = myReq.GetResponse();
   Stream stream = myResp.GetResponseStream();
   BinaryReader br = new BinaryReader(stream);
   byte[] b = br.ReadBytes(500000);
   br.Close();
   myResp.Close();
   return b;
 }
Method สำหรับแสดงรูปภาพ :
private void Display(byte[] input)
{
   MemoryStream stream = new MemoryStream(input);
   Image img = Image.FromStream(stream);
   pictureBox1.Image = img;
   stream.Close();
}
คำสั่งสำหรับปุ่ม button_show :
private void button_show_Click(object sender, EventArgs e)
{
   Display(DownloadData(textBox1.Text));
}
Source code ของโปรแกรมทั้งหมด :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static public byte[] DownloadData(string url)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                WebResponse myResp = myReq.GetResponse();
                Stream stream = myResp.GetResponseStream();
                BinaryReader br = new BinaryReader(stream);
                byte[] b = br.ReadBytes(500000);
                br.Close();
                myResp.Close();
                return b;
            }
            catch
            {
                return null;
            }
        }

        private void Display(byte[] input)
        {
            try
            {
                MemoryStream stream = new MemoryStream(input);
                Image img = Image.FromStream(stream);
                pictureBox1.Image = img;
                stream.Close();
            }
            catch { }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button_show_Click(object sender, EventArgs e)
        {
            Display(DownloadData(textBox1.Text));
        }
    }
}

No comments:

Post a Comment