与WPF BitmapSource
, ,对底层流没有确定性的处理,因此只要有引用,您就可能最终得到锁。
You --> XImage --> BitmapSource --> Stream
如果您调用 dispose XImage
, ,它将在 BitmapSource
, ,这将允许它在 GC 需要时完成。
您可以通过提供流代替路径并显式关闭文件来控制何时关闭文件。过早这样做会导致异常 BitmapSource
, 但是,请确保您没有使用 BitmapSource
关闭流后。
using (var fsImage = File.Open(tiff_path, FileMode.Open, FileAccess.Read, FileShare.None))
{
var output = new PdfDocument();
var input = PdfReader.Open(template_path, PdfDocumentOpenMode.Import);
var page = input.Pages[0];
output.AddPage(page);
page = output.Pages[0];
var gfx = XGraphics.FromPdfPage(page);
var bitmapSource = new BitmapImage();
bitmapSource.BeginInit();
bitmapSource.StreamSource = fsImage;
bitmapSource.EndInit();
using (var image = XImage.FromBitmapSource(bitmapSource))
{
gfx.DrawImage(image, 500, 200, 400, 400);
}
output.Save(destination_path);
output.Close();
}
如果您的图像足够小,您可以跳过流并仅使用 BitmapCacheOption
的 OnLoad
打开后关闭源,但这会导致整个图像被加载到内存中。