首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C# WinForms 開發:OpenFileDialog 與 PictureBox 完整應用指南

     編輯:ASP.NET 基礎

前言

在 Windows Forms 應用程式中,`OpenFileDialog` 與 `PictureBox` 是處理檔案選取與圖片顯示的核心控制項。本文將詳細說明兩者的屬性設定、常見用法與進階技巧。

一、OpenFileDialog 核心屬性與基本用法

基本程式碼範例

string resultFile = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = @"D:\Patch";
openFileDialog1.Filter = "所有檔案 (*.*)|*.*|文字檔 (*.txt)|*.txt";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    resultFile = openFileDialog1.FileName;
    // resultFile 即為使用者選取的完整檔案路徑
}

常用屬性詳細說明

屬性說明
InitialDirectory對話方塊開啟時的初始目錄
Filter檔案篩選器,格式:「描述|副檔名|描述|副檔名」
FilterIndex預設選取的篩選器索引(從 1 開始)
RestoreDirectory關閉對話方塊前是否還原目前目錄
FileName預設顯示或最後選取的檔案名稱
Title對話方塊標題列文字
AddExtension是否自動附加預設副檔名
CheckPathExists關閉前檢查路徑是否存在
DefaultExt預設副檔名
DereferenceLinks是否解析捷徑
ShowHelp是否顯示「說明」按鈕
ValidateNames檢查檔名是否包含無效字元

進階篩選器:一次選取多種副檔名

// 影像檔案篩選器:允許同時選取 BMP、JPG、GIF
dlg.Filter = "Image Files (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";

二、PictureBox 圖片顯示與縮放技巧

SizeMode 屬性完整對照

列舉值常數行為說明
Normal0圖片置於左上角,超過控制項範圍會被裁切
StretchImage1強制拉伸/縮小填滿控制項,可能變形
AutoSize2控制項大小自動調整為圖片原始尺寸
CenterImage3置中顯示,超出範圍裁切
Zoom4保持比例縮放,完整顯示於控制項內(最常用)

程式碼動態產生縮圖(不依賴 SizeMode)

/// <summary>
/// 產生指定尺寸的縮圖
/// </summary>
public Image GetNewImage(int newWidth, int newHeight, Image srcImage)
{
    // 取得縮圖(高品質)
    Image newImg = srcImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
    
    // 使用 Graphics 繪製確保品質
    using (Graphics gr = Graphics.FromImage(newImg))
    {
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        gr.DrawImage(newImg, 0, 0, newWidth, newHeight);
    }
    return newImg;
}

// 使用方式
pictureBox1.Image = GetNewImage(300, 200, originalImage);

建議: 實務上直接設定 `pictureBox1.SizeMode = PictureBoxSizeMode.Zoom` 即可滿足大多數等比例縮放需求,無需手動處理縮圖。

三、完整整合範例:選取圖片並顯示

private void btnSelectImage_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        ofd.Filter = "圖片檔案|*.jpg;*.jpeg;*.png;*.bmp;*.gif|所有檔案|*.*";
        ofd.Title = "請選取圖片";
        
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                pictureBox1.Image = Image.FromFile(ofd.FileName);
                lblFilePath.Text = ofd.FileName;
            }
            catch (Exception ex)
            {
                MessageBox.Show("載入圖片失敗:" + ex.Message);
            }
        }
    }
}

總結

掌握 `OpenFileDialog` 的篩選器設定與 `PictureBox` 的 `SizeMode` 行為,能快速建立良好的檔案選取與圖片瀏覽體驗。搭配 `Zoom` 模式與基本錯誤處理,即可應付大多數 WinForms 圖片處理情境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved