我对在WinForms中加载PictureBox中的图像有一点疑问
我想在我的表单PictureBox
上显示文件系统中的图像文件,例如form1
。
我正在使用C#进行Windows应用程序。
我想查看文件类型,也可以说是pdf / text / png / gif / jpeg。
是否可以使用C#以编程方式从文件系统打开文件?
如果有人知道,请提供任何想法或示例代码。
修改后的代码:我这样做是为了在我的系统中打开文件,但我不知道如何附加文件并附加文件。
private void button1_Click(object sender, EventArgs e)
{
string filepath = @"D:\";
openFileDialog1.Filter = "Image Files (*.jpg)|*.jpg|(*.png)|*.png|(*.gif)|*.gif|(*.jpeg)|*.jpeg|";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
try
{
}
}
}
我不知道我必须在try
块中写什么。任何人都可以帮忙吗?
答案 0 :(得分:2)
使用Image.ImageFromFile http://msdn.microsoft.com/en-us/library/system.drawing.image.fromfile.aspx方法
图片img = Image.ImageFromFile(openFileDialog1.FileName);
应该工作。
修改强>
如果您要将其设置为PictureBox,并在其中查看完整内容,请使用picturebox
SizeMode财产。
答案 1 :(得分:0)
using System.IO;
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Data file"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
try
{
string filename = openFileDialog1.FileName;
FileStream fs=new FileStream(filename, FileMode.Open, FileAccess.Read); //set file stream
Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
MemoryStream stream = new MemoryStream(bindata);//load picture
stream.Position = 0;
pictureBox1.Image = Image.FromStream(stream);
}
}