C# 檔案 載入 System.Drawing.Bitmap [列印支持的物件]

C# 檔案 載入 System.Drawing.Bitmap [列印支持的物件]

C# 檔案 載入 System.Drawing.Bitmap [列印支持的物件]


資料來源: https://gemini.google.com/share/b736479a291e


code

using System;
using System.Drawing; // 引用 System.Drawing.Common
using System.Drawing.Printing;
using System.IO;

public class ImagePrinter
{
    private string _filePath = @"C:\Images\sample.jpg";

    public void LoadAndPrint()
    {
        // 檢查檔案是否存在
        if (!File.Exists(_filePath))
        {
            Console.WriteLine("找不到檔案!");
            return;
        }

        // 使用 using 確保資源釋放 (System.Drawing 非常消耗 Unmanaged 資源)
        using (Bitmap bitmap = new Bitmap(_filePath))
        {
            Console.WriteLine($"圖片已載入: {bitmap.Width}x{bitmap.Height}");

            // 執行列印邏輯
            PrintImage(bitmap);
        }
    }

    private void PrintImage(Bitmap bitmap)
    {
        PrintDocument pd = new PrintDocument();
        
        pd.PrintPage += (sender, e) =>
        {
            // 將圖片繪製到印表機頁面上
            // e.Graphics 是列印的核心畫布
            e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
        };

        try 
        {
            pd.Print();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"列印失敗: {ex.Message}");
        }
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *