Загрузка и отображение картинки в Windows Forms c C#
 
			Доброго времени суток!
В данном примере я покажу Вам как можно загрузить картинку из Интернета и отобразить ее в пользовательском интерфейсе. Изображение будет отображаться при нажатии на кнопку причем, каждый раз будет новое изображение.
Итак, ко:
Интерфейс MainForm.Designer.cs
namespace ShowImagwFromInternetWinForm
{
    partial class MainForm
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows Form Designer generated code
        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ImagePictureBox = new System.Windows.Forms.PictureBox();
            this.DownloadImageButton = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.ImagePictureBox)).BeginInit();
            this.SuspendLayout();
            // 
            // ImagePictureBox
            // 
            this.ImagePictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.ImagePictureBox.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.ImagePictureBox.Location = new System.Drawing.Point(12, 12);
            this.ImagePictureBox.Name = "ImagePictureBox";
            this.ImagePictureBox.Size = new System.Drawing.Size(435, 462);
            this.ImagePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.ImagePictureBox.TabIndex = 0;
            this.ImagePictureBox.TabStop = false;
            // 
            // DonwloadImageButton
            // 
            this.DownloadImageButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.DownloadImageButton.Cursor = System.Windows.Forms.Cursors.Hand;
            this.DownloadImageButton.Location = new System.Drawing.Point(12, 496);
            this.DownloadImageButton.Name = "DonwloadImageButton";
            this.DownloadImageButton.Size = new System.Drawing.Size(435, 49);
            this.DownloadImageButton.TabIndex = 1;
            this.DownloadImageButton.Text = "Загрузить";
            this.DownloadImageButton.UseVisualStyleBackColor = true;
            this.DownloadImageButton.Click += new System.EventHandler(this.DonwloadImageButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 19F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(459, 557);
            this.Controls.Add(this.DownloadImageButton);
            this.Controls.Add(this.ImagePictureBox);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Главное окно";
            ((System.ComponentModel.ISupportInitialize)(this.ImagePictureBox)).EndInit();
            this.ResumeLayout(false);
        }
        #endregion
        private PictureBox ImagePictureBox;
        private Button DownloadImageButton;
    }
}
Код формы с логикой программы
using System.Net.Http;
namespace ShowImagwFromInternetWinForm
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        /**
         * Загружает изображение 
         * и возвращает его как массив байт
         * 
         */
        private static byte[] DownloadImage(string url)
        {
            using var httpClient = new HttpClient();
            var response = httpClient.GetByteArrayAsync(url).Result;
            return response;
        }
        /**
         * 
         * Обработчик нажатия кнопки загрзки
         * 
         */
        private void DonwloadImageButton_Click(object sender, EventArgs e)
        {
            DownloadImageButton.Text = "Картинка загружается...";
            // вызываем загрузку внутри отдельной задачи, чтобы не блокировать интерфейс
            Task.Run(() =>
            {
                // загружаем картинку
                var imageBytes = DownloadImage("https://source.unsplash.com/random");
                // создаем объект Bitmap из массива байт
                var bitmap = new Bitmap(new MemoryStream(imageBytes));
                // Устанавливаем изображение для отображение пользователю
                ImagePictureBox.Image = bitmap;
                DownloadImageButton.Text = "Загрузить";
            });
        }
    }
}
Таким образом, при запуске этой программы Вы увидите пустое окно, в которое при нажатии на кнопку будет загружено изображение.
- 
					Создано 23.08.2022 08:29:08  
- 
					 Михаил Русаков Михаил Русаков
 
			 
			 
		 
				 
			 
				 
				 
				 
				
Комментарии (0):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.