Как вставить картинку в windows forms c

от admin

Как вставить картинку в windows forms c

PictureBox предназначен для показа изображений. Он позволяет отобразить файлы в формате bmp, jpg, gif, а также метафайлы ищображений и иконки. Для установки изображения в PictureBox можно использовать ряд свойств:

Image : устанавливает объект типа Image

ImageLocation : устанавливает путь к изображению на диске или в интернете

InitialImage : некоторое начальное изображение, которое будет отображаться во время загрузки главного изображения, которое хранится в свойстве Image

ErrorImage : изображение, которое отображается, если основное изображение не удалось загрузить в PictureBox

Чтобы установить изображение в Visual Studio, надо в панели Свойств PictureBox выбрать свойство Image. В этом случае нам откроется окно импорта изображения в проект, где мы собственно и сможем выбрать нужное изображение на компьютере и установить его для PictureBox:

И затем мы сможем увидеть данное изображение в PictureBox:

Элемент PictureBox в Windows Forms

Либо можно загрузить изображение в коде:

Размер изображения

Для установки изображения в PictureBox используется свойство SizeMode , которое принимает следующие значения:

Normal : изображение позиционируется в левом верхнем углу PictureBox, и размер изображения не изменяется. Если PictureBox больше размеров изображения, то по справа и снизу появляются пустоты, если меньше — то изображение обрезается

StretchImage : изображение растягивается или сжимается таким обраом, чобы вместиться по всей ширине и высоте элемента PictureBox

AutoSize : элемент PictureBox автоматически растягивается, подстраиваясь под размеры изображения

CenterImage : если PictureBox меньше изображения, то изображение обрезается по краям и выводится только его центральная часть. Если же PictureBox больше изображения, то оно позиционируется по центру.

Zoom : изоражение подстраивается под размеры PictureBox, сохраняя при этом пропорции

Загрузка и отображение картинки в Windows Forms c C#

Загрузка и отображение картинки в 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);

private PictureBox ImagePictureBox;
private Button DownloadImageButton;
>
>

Код формы с логикой программы

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;

/**
*
* Обработчик нажатия кнопки загрзки
*
*/
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;

Таким образом, при запуске этой программы Вы увидите пустое окно, в которое при нажатии на кнопку будет загружено изображение.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Она выглядит вот так:

Комментарии ( 0 ):

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

Display an image into windows forms

I wanted to display an image to the windows forms, but i already did this and the image did not come out.

Where did I go wrong?

Here is the code:

4 Answers 4

    Like you are doing.

Using ImageLocation property of the PictureBox like:

Using an image from the web like:

And please, be sure that «../SamuderaJayaMotor.png» is the correct path of the image that you are using.

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent() ?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

dotNET's user avatar

I display images in windows forms when I put it in Load event like this:

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Читать:
Dataviz что за программа

C# – How to use PictureBox control?

PictureBox control is used to display the picture. Once we place the control on Windows Form, we need to set the right properties to load & display the image on the PictureBox control. We use this control when we need to deal with the images. It acts as a container for the loaded images, and it provides the necessary properties & methods to load the images. Through this article, we are going to discuss the usage of PictureBox control.

Properties of the PictureBox control

Add Image to the PictureBox control

The control, the name tells us, deals with the images. So, it provides the required properties to load the images to the control. Few of the frequently used properties, we will discuss here.

Image property is used to assign the image to this control. We can load images to PictureBox control, during Design time or through the code.

Image property is of Image class type. Hence, in the code, we can not directly assign the image path, to this property. We have to write the code, which should load the image first, from the given location, and then assign the Image object to this property, to display the image on the control. For this, Image class provides, FromFile method to us. This method takes a single argument, path, or URL of the image and returns the Image object. Here is the code snippet to map the image to the control;

It is simple right? But, if you want the image to be part of the Project; you can import the image into the project, and then assign it to the control in design mode.

ImageLocation is another property, which we can use to give the path of the image (or URL of the image); then, the control loads it & display the image. Below is an example;

InitialImage property is used to set an alternate image when the main image is loading to display. Usually, we set the low-resolution image to this property; so, that it will be quickly displayed on the control. Meanwhile, a high-resolution image set to the control will be loaded.

During the image load, if any error is encountered, the image will fail to load. We can use ErrorImage property to set the error image and this will be displayed when an error is encountered, to indicate to the user that the image load was failed.

How to resize the image?

Another important, frequently used property is its SizeMode property. This property controls the way the image is displayed on the PictureBox control. It is of PictureBoxSizeMode enum type. Depending on the value we give, this control will control the display of the image. Here are the valid values and their meaning;

  • Normal – The image will display as it is, from the top-left corner of the control. If the size of the image is bigger than the control display size, the control will clip the image; we see only the portion of the image.
  • StretchImage – This has elastic nature. When set, the control stretches the image to fit into the size of the control. Remember that, this option, doesn’t maintain the size ratio (or aspect ratio); it simply stretches or shrinks the image to fit into the boundaries of the control.
  • AutoSize – When setting this, the image will be displayed as Normal; but, when the image size is different than the PictureBox control size, the control size will adjust accordingly. Got it? With other size mode values, an image within the control will be adjusted; whereas with this AutoSize value, the control size will be adjusted depending on the size of the image.
  • CenterImage – Image center is in the center of the control. Image center? That’s correct. The Center of the image will be displayed in the center of the control. If the image size is bigger than the size of the control; the outer edges of the image will be clipped.
  • Zoom – This option will resize the image in the control. Unlike StretchImage, this maintains the aspect or size ratio. Hence, the image looks good, compared to the image displayed with the value StretchImage .

Let’s look at some frequently used methods.

Methods of PictureBox control

Loading image to the control

Load method is used to load the image from the specified path or URL. For example, we can load the image from the internet, by specifying the complete path of the image;

LoadAsync is an important method we use, to load the image asynchronously to allow other statements to continue to execute during the image load. You can use this when the image size is too big and takes time to load. Above code, we can write it as below;

CancelAsync() method is used to cancel the asynchronous load of the image to the control.

Like other Windows Forms controls, this control also triggers the events. Here are the few commonly used ones;

PictureBox control Events

LoadCompleted event will be triggered when the asynchronous image load is completed. We can use LoadProgressChanged event to show the progress of the asynchronous image load to the user. These two events will be triggered, when we use, LoadAsync method(s) to load the images.

Click event will be triggered when we click on the control.

Let’s put all together, what we have learned so far about this control; and prepare the simple application. Here is the working code;

Here is the screenshot of the Application;

Usage of PictureBox Control

Usage of PictureBox Control

Похожие статьи