如何将随机图像加载并显示到c#中的图片框中? [英] How to load and show random images into a picture box in c# ?
本文介绍了如何将随机图像加载并显示到c#中的图片框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个应用程序,当我点击一个按钮时,一些位图图片会从特定位置随机加载并显示在pictureBox中!怎么做?
我的代码已经是这样的:
I am making an application, that when i click a button, some bitmap pictures load randomly from a specific location and be shown in a pictureBox ! How to do it ?
my code is already like this :
using System;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MLP_OCR
{
public partial class Form1 : Form
{
int index = -1;
List<Image> images;
public Form1()
{
InitializeComponent();
images = new List<Image>();
DirectoryInfo di = new DirectoryInfo(@"F:\bmp"); // give path
FileInfo[] finfos = di.GetFiles("*.bmp", SearchOption.AllDirectories);
foreach (FileInfo fi in finfos)
images.Add(Image.FromFile(fi.FullName));
}
private async void trainButton_Click(object sender, EventArgs e)
{
for (index=-1; index < 1699; index++)
{
//index++;
if (index < 0 || index >= images.Count)
index = 0;
samplePictureBox.Image = images[index];
await Task.Delay(2);
}
}
}
}
推荐答案
如果你使用图像路线,您可以使用列表 images = new List ()创建图像列表;并使用images.Add(image)添加每个图像。对于每个图像。
If you're using the Image route, you can create a list of images with List images = new List(); and add each image to it with images.Add(image); for each image.
For Images:
Random random = new Random();
samplePictureBox.Image = images[random.Next(0, images.Count - 1)];
试试这个:
Try this:
private Random rand = new Random();
...
public void GetRandomImage()
{
string[] files = Directory.GetFiles(@"D:\Temp\", "*.jpg", SearchOption.AllDirectories);
myPictureBox.Image = Image.FromFile(files[rand.Next(files.Length)]);
}
- 创建图像名称列表(您可以使用 DirectoryInfo.EnumerateFiles方法 [ ^ ]以实现它。)
- 在
0
和(List.Count-1)之间选择一个随机数
。r
- 加载并显示与列表项
r
相对应的图像。 - 等待按钮单击
- 转到第2点。
- Create a list of image names (you may use the DirectoryInfo.EnumerateFiles method[^] in order to accomplish it).
- Pick a random number
r
, between0
and(List.Count-1)
. - Load and show the image corrensponding to the item
r
of the list. - Wait for button click
- Go to point 2.
这篇关于如何将随机图像加载并显示到c#中的图片框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文