Menampilkan Image Dari Web Ke Dalam Form
Dalam beberapa kasus, mungkin ada kalanya kita ingin menampilkan sebuah gambar yang lokasinya di website yang kemudian ingin kita tampilkan di form secara langsung atau istilah kerennya Streaming Image From Web.
Buatlah sebuah method di form sebagai berikut:
/// <summary> /// Streams the image from URL. /// </summary> /// <param name="psUrl">The ps URL.</param> /// <returns></returns> public Image StreamImageFromUrl(string psUrl) { WebResponse result = null; Image rImage = null; try { WebRequest request = WebRequest.Create(psUrl); byte[] rBytes; result = request.GetResponse(); Stream rStream = result.GetResponseStream(); using (var br = new BinaryReader(rStream)) { rBytes = br.ReadBytes(1000000); br.Close(); } result.Close(); using (var imageStream = new MemoryStream(rBytes, 0, rBytes.Length)) { imageStream.Write(rBytes, 0, rBytes.Length); rImage = Image.FromStream(imageStream, true); imageStream.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (result != null) { result.Close(); } } return rImage; }
Kemudian jangan lupa untuk menambahkan using-nya sbb:
using System.Drawing; using System.IO; using System.Net;
Dan bila kita lihat hasil formnya adalah sebagai berikut:
Kode selengkapnya sebagai berikut:
using System; using System.Drawing; using System.IO; using System.Net; using System.Windows.Forms; namespace ImageTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Image StreamImageFromUrl(string psUrl) { WebResponse result = null; Image rImage = null; try { WebRequest request = WebRequest.Create(psUrl); byte[] rBytes; result = request.GetResponse(); Stream rStream = result.GetResponseStream(); using (var br = new BinaryReader(rStream)) { rBytes = br.ReadBytes(1000000); br.Close(); } result.Close(); using (var imageStream = new MemoryStream(rBytes, 0, rBytes.Length)) { imageStream.Write(rBytes, 0, rBytes.Length); rImage = Image.FromStream(imageStream, true); imageStream.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (result != null) { result.Close(); } } return rImage; } private void button1_Click(object sender, EventArgs e) { pnlImage.BackgroundImage = StreamImageFromUrl(txtImageUrl.Text.Trim()); pnlImage.BackgroundImageLayout = ImageLayout.Zoom; } } }
Pertanyaan selanjutnya, lalu bagaimanakah bila url dari image yang ingin kita tampilkan ke dalam form adalah dari alamat FTP, maka berikut ini adalah caranya:
/// <summary> /// Streams the image from FTP address. /// </summary> /// <param name="ftpaddress">The ftpaddress.</param> /// <returns></returns> public Image StreamImageFromFtpAddress(string ftpaddress) { var wReq = (FtpWebRequest)WebRequest.Create(ftpaddress); var wRes = (FtpWebResponse)(wReq).GetResponse(); using (Stream str = wRes.GetResponseStream()) { return Image.FromStream(str); } }
Selamat belajar dan semoga bermanfaat.
Leave a Reply
Want to join the discussion?Feel free to contribute!