PictureBox
A PictureBox shows an image: a logo, a photograph, a preview of a document, an icon in a list. It is a control like any other, so it sits in the layout, takes the focus if it is asked to, and raises Click. Two of its properties decide almost everything a user sees: the image and the way the control fits the image into its rectangle.
A picture on a form
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
public Form1()
{
Text = "A preview";
ClientSize = new Size(360, 280);
var photo = new PictureBox
{
Location = new Point(16, 16),
Size = new Size(160, 120),
SizeMode = PictureBoxSizeMode.Zoom,
BorderStyle = BorderStyle.FixedSingle,
ImageLocation = "cover.png",
WaitOnLoad = true,
};
var caption = new Label
{
Text = "cover.png, 160 by 120, zoomed",
Location = new Point(16, 144),
AutoSize = true,
};
var thumb = new PictureBox
{
Location = new Point(200, 16),
Size = new Size(64, 64),
SizeMode = PictureBoxSizeMode.CenterImage,
Image = SystemIcons.Information.ToBitmap(),
TabStop = false,
};
Controls.Add(photo);
Controls.Add(caption);
Controls.Add(thumb);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The first box loads cover.png from the working directory of the program, which fails at run time when the file is not there, and WaitOnLoad = true makes that failure appear while the form is created rather than later. The second box takes an image that ships with Windows, SystemIcons.Information, and shows it at its own size, centred in the square. TabStop = false keeps a picture out of the tab order, which is almost always what a decorative image wants.
The five size modes
- PictureBoxSizeMode.Normal: the image is drawn at its own size from the top-left corner and is cut off at the edge of the control.
- PictureBoxSizeMode.StretchImage: the image fills the control exactly, and is distorted if the proportions differ.
- PictureBoxSizeMode.AutoSize: the control grows to the image. It is the only mode in which the image is never cut, and the layout has to accept the size that comes back.
- PictureBoxSizeMode.CenterImage: the image is drawn at its own size, centred, and cut if the control is smaller.
- PictureBoxSizeMode.Zoom: the image is scaled to fit inside the control, keeping its proportions. This is the one a preview wants.
For a thumbnail gallery the arithmetic is worth knowing: Zoom scales by the smaller of the two ratios, control width to image width and control height to image height, so the result touches one pair of edges and leaves a margin on the other.
Loading and the file lock
An image can arrive three ways: from a file by name (ImageLocation), from an Image object the code builds or loads, and from a resource embedded in the assembly. The file route has a trap that every WinForms programmer meets once:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly PictureBox _box = new()
{
Location = new Point(16, 16),
Size = new Size(160, 120),
SizeMode = PictureBoxSizeMode.Zoom,
};
private readonly Label _status = new() { Location = new Point(16, 144), AutoSize = true };
public Form1()
{
Text = "Load and replace";
ClientSize = new Size(360, 200);
var open = new Button { Text = "Open", Location = new Point(16, 160) };
open.Click += (sender, e) => Load("cover.png");
Controls.Add(_box);
Controls.Add(_status);
Controls.Add(open);
}
private void Load(string path)
{
_box.Image?.Dispose();
_box.Image = null;
if (!File.Exists(path))
{
_status.Text = $"{path} is not there";
return;
}
using var stream = File.OpenRead(path);
_box.Image = Image.FromStream(stream);
_status.Text = $"{path}: {_box.Image.Width} by {_box.Image.Height}";
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. The File.OpenRead route is the fix for the lock: Image.FromFile keeps the file open for as long as the image lives, so the program cannot overwrite the file it is showing, and Delete fails with a sharing violation. Reading the bytes into an image through a stream releases the file as soon as the stream is closed. The Dispose of the old image matters for the same reason in reverse: every Image owns an unmanaged handle.
An image embedded in the assembly has neither problem and is what a form's icons and logos use. The designer writes it into Form1.resx as a ResXFileRef and the build embeds it; the code reads it with new Bitmap(typeof(Form1), "Resources.cover.png").
A file check that runs
The decision "is this file an image I can show" is the application's, and it needs no System.Drawing at all. This program creates a file and classifies four names, and it runs here:
using System;
using System.IO;
var folder = Path.Combine(Path.GetTempPath(), "pictures-demo");
Directory.CreateDirectory(folder);
var png = Path.Combine(folder, "logo.png");
File.WriteAllBytes(png, new byte[] { 0x89, 0x50, 0x4E, 0x47 });
Console.WriteLine($"created {Path.GetFileName(png)}: {new FileInfo(png).Length} bytes");
foreach (var name in new[] { "logo.png", "photo.jpg", "notes.txt", "icon" })
{
Console.WriteLine($"{name,-10} {Describe(name)}");
}
static string Describe(string name)
{
var extension = Path.GetExtension(name).ToLowerInvariant();
var image = extension is ".png" or ".jpg" or ".jpeg" or ".bmp" or ".gif";
return image ? $"an image, {extension}" : "not an image";
}
dotnet run
created logo.png: 4 bytes
logo.png an image, .png
photo.jpg an image, .jpg
notes.txt not an image
icon not an image
The output is the real run. The check is by extension, which is a guess and enough for a file picker's filter; a program that must be sure reads the first bytes of the file, because an extension is a name and not a format. The empty icon row is the case a filter must handle: Path.GetExtension gives an empty string and the classification is a plain no.
Exercises
- Add "photo.jpeg" and "picture.PNG" to the list and run the program.
- Make Describe also refuse a file that does not exist, and run it with one name that is not there.
- Explain from the documentation why Image.FromFile keeps the file locked and what the stream route changes.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which SizeMode scales an image to fit the control without distorting it?
Answer
Zoom
Zoom keeps the proportions; StretchImage fills the rectangle exactly.
-
Which SizeMode makes the control grow to the image?
Answer
AutoSize
The control takes the image's size, and the layout has to accept it.
-
Which SizeMode centres an image at its own size?
Answer
CenterImage
Normal draws from the corner; CenterImage centres it and cuts the edges.
-
What does ImageLocation do?
Answer
Names a file the control loads as its image
It is the by-name route, and WaitOnLoad makes the load synchronous.
-
Why is Image.FromFile a trap?
Answer
It keeps the file locked while the image lives
The stream route releases the file as soon as the stream closes.
-
What does WaitOnLoad = true change?
Answer
The image is loaded while the form is created, not in the background
A missing file then fails at construction, which is easier to see.
-
What is ErrorImage for?
Answer
An image shown when the real one cannot be loaded
It gives a broken load something to display instead of an empty rectangle.
-
What did the run print for notes.txt?
Answer
not an image
The extension list has no .txt in it.
-
Why is an extension check only a guess?
Answer
The extension is a name; the format is in the first bytes of the file
A file named .png can hold anything, which is why a strict reader checks the signature.
-
What does TabStop = false on a PictureBox do?
Answer
Keeps a decorative image out of the tab order
A picture that cannot be used with the keyboard should not take the focus.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev