2012-08-07 35 views
1

我希望能夠使用其他UIElements打印圖像。我有一個固定頁面的實例,並試圖添加圖像像這樣將圖像添加到WPF中的固定頁面

// Basic printing stuff 
var printDialog = new PrintDialog(); 
var fixedDocument = new FixedDocument(); 
fixedDocument.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); 

FixedPage page = new FixedPage(); 
page.Width = fixedDocument.DocumentPaginator.PageSize.Width; 
page.Height = fixedDocument.DocumentPaginator.PageSize.Height; 

Image img = new Image(); 

// PrintIt my project's name, Img folder 
var uriImageSource = new Uri(@"/PrintIt;component/Img/Stuff.png", UriKind.RelativeOrAbsolute); 
img.Source = new BitmapImage(uriImageSource); 
img.Width = 100; 
img.Height = 100; 

page.Children.Add(img); 

PageContent pageContent = new PageContent(); 
((IAddChild)pageContent).AddChild(page); 

fixedDocument.Pages.Add(pageContent); 

// Print me an image please! 
_printDialog.PrintDocument(fixedDocument.DocumentPaginator, "Print"); 

它給了我一個白紙。我想知道爲什麼,因爲其他UIElements(如TextBox,Grid,Rect)沒有問題。我錯過了什麼?

謝謝!

PS好的,我找到了另一個解決方案。我不知道爲什麼,但與該Uri一張照片正確加載

var uri = new Uri("pack://application:,,,/Img/Stuff.png"); 

回答

3

爲了更清楚我的代碼

var bitImage = new BitmapImage(); 
bitImage.BeginInit(); 
bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read); 
bitImage.DecodePixelWidth = 250; 
bitImage.CacheOption = BitmapCacheOption.OnLoad; 
bitImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; 
bitImage.EndInit(); 
bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin); 
bitImage.Freeze(); 

var tempImage = new Image {Source = bitImage}; 
var imageObject = new ImageObject(tempImage, fileName); 
bitImage.StreamSource.Dispose(); 
page.Children.Add(imageObject); 
+1

隨着StreamSource的,它的工作!謝謝你,兄弟。 – Semuserable 2012-08-07 20:41:33

+0

只需要注意:在「大」(=大量頁面)上運行此代碼的FixedDocument時,代碼不會拋出OutOfMemoryExceptions。他們只是被忽略,圖像不顯示。該行爲是不同的這個代碼:BitmapFrame bitImage = BitmapFrame.Create(新的FileStream(文件名,FileMode.Open,FileAccess.Read),BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.OnLoad); – 2016-02-04 09:11:12

0

首先,我想建議,見下文。

Set the sourceStream of the Image for BitMap 
    bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read); 

然後凍結BitMap圖像,或者它不會作爲可渲染圖像在實例中。

bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin); 
bitImage.Freeze(); 

這應該工作,如果不是我個人認爲這是一個壞主意,直接使用位圖的工作中,我使用位圖來創建圖像格式文件,然後將其複製到該類型的圖像(System.Drawing中iguess),東西像下面那樣

var tempImage = new Image {Source = bitImage}; 
var imageObject = new ImageObject(tempImage, fileName); 
bitImage.StreamSource.Dispose(); 

這個tempImage可以作爲普通的UIElement添加到你的頁面。 希望它有幫助。