gpt4 book ai didi

c# - 一张一张导入显示图片

转载 作者:太空狗 更新时间:2023-10-30 01:36:34 24 4
gpt4 key购买 nike

我有一个用于导入和显示多个图像的 C# 窗口窗体。

我能够导入多张图片并显示第一张图片,但在一张一张地显示图片时遇到一些问题。

程序流程:用户点击按钮,然后选择多张图片。之后,第一张图片应该显示在图片框上。当用户单击“下一张图片按钮”时,应显示下一张图片。

第一张图片可以显示在图片框上,但不知道如何逐张显示。是否有实现此目的的配置或如何通过编码实现它。谢谢大家。

我的编码:

public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
InitializeOpenFileDialog();
}

private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";

// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}

private void SelectFileButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(file);
pb.Height = loadedImage.Height;
pb.Width = loadedImage.Width;
pb.Image = loadedImage;
flowLayoutPanel1.Controls.Add(pb);
}

}
}
}

最佳答案

恕我直言,有更好的方法可以实现这一目标。

您不必为每个 图像添加PictureBox 控件,它会使您的表单重载。我的建议是保留所有已加载图像的列表,以及当前显示图像的索引器。

代码:

PictureBox 添加到您的表单(我们称之为 pictureBox1),您希望在其中显示图像。

此外,将这些属性添加到您的类中:

private List<Image> loadedImages = new List<Image>();
private int currentImageIndex;

在您的“加载图片”按钮点击事件中:

private void SelectFileButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
loadedImages.Clear();

// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
loadedImages.Add(Image.FromFile(file));
}

if (loadedImages.Count > 0)
{
currentImageIndex = 0;
pictureBox1.Image= loadedImages[currentImageIndex];
}
}
}

最后,对于下一个/上一个按钮的单击事件,您可以添加以下代码:

// Mod function to support negative values (for the back button).
int mod(int a, int b)
{
return (a % b + b) % b;
}

// Show the next picture in the PictureBox.
private void button_next_Click(object sender, EventArgs e)
{
currentImageIndex = mod(currentImageIndex + 1, loadedImages.Count);
pictureBox1.Image = loadedImages[currentImageIndex];
}

// Show the previous picture in the PictureBox.
private void button_prev_Click(object sender, EventArgs e)
{
currentImageIndex = mod(currentImageIndex - 1, loadedImages.Count);
pictureBox1.Image = loadedImages[currentImageIndex];
}

关于c# - 一张一张导入显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21751276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com