C#利用Picturebox控件显示图片

    2025-05-18 01:56:07

    C#利用Picturebox控件显示图片

    1、Picturebox控件SizeMode属性

    (1)Normal模式:如果图片大于Picturebox控件大小,图片不能完全显示

    (2)AutoSize:自动调整Picturebox控件大小去适应图片的大小,图片可以完全显示。

    (3)StretchImage:Picturebox控件大小不变,自动调整图像适应控件。

    2、使用的类

    (1)OpenFileDialog 类

    提示用户打开文件。无法继承此类。

    public sealed class OpenFileDialog : FileDialog

    OpenFileDialog 类的属性:

    Filter :获取或设置当前文件名筛选器字符串,该字符串决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容。(从 FileDialog 继承。)FilterIndex :获取或设置文件对话框中当前选定筛选器的索引。(从 FileDialog 继承。)FileName :获取或设置一个包含在文件对话框中选定的文件名的字符串。(从 FileDialog 继承。)FileNames:获取对话框中所有选定文件的文件名。(从 FileDialog 继承。)

    OpenFileDialog 类的公共方法:

    ShowDialog 已重载。 运行通用对话框。 (从 CommonDialog 继承。)

    (2)SaveFileDialog 类

    提供一个对话框,用户使用该对话框可指定保存文件时使用的选项。

    SaveFileDialog 类属性:

    Filter:获取或设置指定要在 SaveFileDialog 中显示的文件类型和说明的筛选器字符串。

    SaveFileDialog 类方法:

    ShowDialog 方法:显示保存对话框控件

    3、实例

    (1)新建一个C#窗体项目,项目名为showPicture,在Form1上添加一个Picturebox控件和两个按钮。

    (2)添加代码

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    namespace showPicture

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    private string pathname = string.Empty; //定义路径名变量

    private void button1_Click(object sender, EventArgs e) //打开方法

    {

    OpenFileDialog file = new OpenFileDialog();

    file.InitialDirectory = ".";

    file.Filter = "所有文件(*.*)|*.*";

    file.ShowDialog();

    if (file.FileName != string.Empty)

    {

    try

    {

    pathname = file.FileName; //获得文件的绝对路径

    this.pictureBox1.Load(pathname);

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    }

    private void button2_Click(object sender, EventArgs e) //保存方法

    {

    SaveFileDialog save = new SaveFileDialog();

    save.ShowDialog();

    if (save.FileName != string.Empty)

    {

    pictureBox1.Image.Save(save.FileName);

    }

    }

    }

    }

    (3)显示效果

    (4)保存方法调用效果