Cách tải và hiển thị ảnh trong WPF bằng Image control

Trong ứng dụng WPF, việc hiển thị hình ảnh có thể thực hiện theo nhiều cách khác nhau tùy vào nguồn gốc của tệp ảnh. Dưới đây là các phương pháp phổ biến:

1. Hiển thị ảnh từ URL mạng

<Image Source="https://example.com/images/photo.jpg" Stretch="UniformToFill" />

2. Sử dụng ảnh đã được thêm vào dự án

<Image Source="Assets/photo.jpg" Stretch="UniformToFill" />

Lưu ý: Tệp ảnh phải được thêm vào dự án và thuộc tính Build Action được đặt là Resource.

3. Tải ảnh từ đường dẫn tương đối (không cần thêm vào dự án)

Sử dụng URI scheme pack://siteoforigin:

<Image Source="pack://siteoforigin:,,,/Images/photo.jpg" />

Trong code-behind:

imageControl.Source = new BitmapImage(
    new Uri("pack://siteoforigin:,,,/Images/photo.jpg", UriKind.Absolute)
);

Kiểu URI này yêu cầu tham số UriKind.Absolute dù đường dẫn là tương đối. Ảnh không cần nằm trong dự án, nhưng phải tồn tại tại thư mục đầu ra khi chạy chương trình.

4. Tải ảnh từ tài nguyên ứng dụng (đã nhúng trong dự án)

imageControl.Source = new BitmapImage(
    new Uri("Assets/photo.jpg", UriKind.Relative)
);

Cú pháp trên tương đương với:

imageControl.Source = new BitmapImage(
    new Uri("pack://application:,,,/Assets/photo.jpg", UriKind.Absolute)
);

Ảnh phải được thêm vào dự án với Build Action = Resource.

5. Tải ảnh từ đường dẫn tuyệt đối trên hệ thống

imageControl.Source = new BitmapImage(
    new Uri(@"C:\Images\photo.jpg", UriKind.Absolute)
);

Hoặc sử dụng URI site-of-origin với ổ đĩa:

imageControl.Source = new BitmapImage(
    new Uri("pack://siteoforigin:,,,/C:/Images/photo.jpg", UriKind.Absolute)
);

6. Duyệt và hiển thị ảnh trong thư mục

Ví dụ: Lấy danh sách ảnh từ thư mục và chuyển đổi qua lại:

public partial class MainWindow : Window
{
    private readonly string[] _imageFiles;
    private int _currentIndex = -1;

    public MainWindow()
    {
        InitializeComponent();
        _imageFiles = Directory.GetFiles("Images", "*.jpg");
    }

    private void OnNextClick(object sender, RoutedEventArgs e)
    {
        _currentIndex = (_currentIndex + 1) % _imageFiles.Length;
        LoadImage(_imageFiles[_currentIndex]);
    }

    private void OnPreviousClick(object sender, RoutedEventArgs e)
    {
        _currentIndex--;
        if (_currentIndex < 0)
            _currentIndex = _imageFiles.Length - 1;
        LoadImage(_imageFiles[_currentIndex]);
    }

    private void LoadImage(string filePath)
    {
        imageControl.Source = new BitmapImage(new Uri(filePath, UriKind.Absolute));
    }
}

Lưu ý: Khi dùng Directory.GetFiles với đường dẫn tương đối như "Images", thư mục này phải tồn tại trong thư mục thực thi (bin/Debug hoặc bin/Release).

Thẻ: WPF C# Image Control BitmapImage URI Pack

Đăng vào ngày 3 tháng 7 lúc 05:23