C# 获取图像的大小
我正在制作一个小的Windows窗体应用程序,从您的电脑中选择一个图像,然后使用文件路径在C# 获取图像的大小,c#,image,visual-studio,C#,Image,Visual Studio,我正在制作一个小的Windows窗体应用程序,从您的电脑中选择一个图像,然后使用文件路径在pictureBox1中显示图像 private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = openFileDialog1.FileName; pictureBox
pictureBox1
中显示图像
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
pictureBox1.ImageLocation = openFileDialog1.FileName;
}
}
现在我想把图像的尺寸(以像素为单位)放到另一个文本框中
我这样做可能吗?试试这个
System.Drawing.Image img = System.Drawing.Image.FromFile(openFileDialog1.FileName);
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);
我认为在使用
ImageLocation
设置图像时,无法获得图像的大小(因为PictureBox在内部处理加载)。尝试使用image.FromFile
加载图像,并使用该文件的Width
和Height
属性
var image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image;
// Now use image.Width and image.Height
使用
image.FromFile
方法打开图像
Image image = Image.FromFile(openFileDialog1.FileName);
将您的图像
放入图片框中
pictureBox1.Image = image;
您需要的是System.Drawing.Image
class。图像的大小在image.size
属性中。但是,如果您想分别获得Width
和Height
,可以分别使用image.Width
和image.Height
然后在另一个TextBox
(假设名称为textBox2
)中,您可以像这样简单地分配Text
属性
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
完整代码:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
Image image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image; //simply put the image here!
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
}
}