2013-08-07 63 views
1

我想打印一個文件中的圖像,以完美地適合頁面。C#:從文件打印圖像

所有我設法代碼,直到如今是這樣的:

private void button_print_Click(object sender, EventArgs e) 
    { 
     if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      printDocument1.PrinterSettings = printDialog1.PrinterSettings; 
      printDocument1.PrintPage += PrintPage; 
      printDocument1.Print();   
     } 
    } 

    private void PrintPage(object o, PrintPageEventArgs e) 
    { 
     System.Drawing.Image img = imgOriginal; 
     Point loc = new Point(0, 24); 
     e.Graphics.DrawImage(img, loc); 

    } 

這裏的問題是,該圖像是往大了完全適合頁面。我能做什麼?所有線索我發現谷歌的問題都不是那麼有希望。

任何想法?

在此先感謝

馬爾科冰霜

+0

所以,你想將圖像調整到默認打印機當前選定的紙張的大小?你想打破縱橫比嗎? –

+0

是的。我想調整它。但我想保持寬高比。 –

+0

你可以嘗試這樣的事情:img.Width = pageSetupDialog.Document.DefaultPageSettings.PaperSize.Width; –

回答

1
private void PrintPage(object o, PrintPageEventArgs e) 
{ 
    string filepath = "D:\\patient images\\" + txtPatCode.Text + "\\" + lstImages.SelectedItems[0].Text; 
    System.Drawing.Image img = Image.FromFile(filepath); 
    ResizeImage(img, 200); 
    Point loc = new Point(200, 200); 
    e.Graphics.DrawImage(img, loc);   
} 

public static Image ResizeImage(Image img, int minsize) 
{ 
    var size = img.Size; 
    if (size.Width >= size.Height) 
    { 
    // Could be: if (size.Height < minsize) size.Height = minsize; 
    size.Height = minsize; 
    size.Width = (size.Height * img.Width + img.Height - 1)/img.Height; 
    } 
    else 
    { 
    size.Width = minsize; 
    size.Height = (size.Width * img.Height + img.Width - 1)/img.Width; 
    } 
    return new Bitmap(img, size); 
} 
+2

您應該將此答案歸因於[調整圖像在C#中的大小](http://stackoverflow.com/a/15998683/719186),因爲您的ResizeImage函數似乎是從它複製的。 – LarsTech