【发布时间】:2018-02-03 09:55:55
【问题描述】:
我有一些图像要打印出来。这些图像可以有不同的格式,从不同的 DPI 到不同的格式(JPEG、PNG 等)
现在我所做的是将图像加载到我的应用程序中并尝试 将 dpi 转换为 96。但是在这个过程中我得到了 OutOfMemoryException,我不知道如何继续。
Private Sub PrintImage(Optional providedPrintDialog As PrintDialog = Nothing)
Dim objPrintDialog As PrintDialog
If providedPrintDialog IsNot Nothing Then
objPrintDialog = providedPrintDialog
Else
objPrintDialog = New PrintDialog()
End If
Dim myPanel As New StackPanel
myPanel.Margin = New Thickness(15)
Dim myImage As New Controls.Image
Dim tempBitmapImage = ConvertBitmapToXDPI(Me.SelectedFileViewModel.File.GetPath, 96)
Dim tempBitmapImageWidth As Integer = CInt(objPrintDialog.PrintableAreaWidth)
' A4 max width = 793
If tempBitmapImage.Width > tempBitmapImageWidth Then
myImage.Stretch = System.Windows.Media.Stretch.Uniform
Else
myImage.Stretch = System.Windows.Media.Stretch.None
End If
myImage.Source = tempBitmapImage
myPanel.Children.Add(myImage)
myPanel.Measure(New System.Windows.Size(objPrintDialog.PrintableAreaWidth, objPrintDialog.PrintableAreaHeight))
myPanel.Arrange(New Rect(New System.Windows.Point(0, 0), myPanel.DesiredSize))
objPrintDialog.PrintVisual(myPanel, "Billede") ' <- OutOfMemoryException thrown here
End Sub
Private Function ConvertBitmapToXDPI(path As String, newDpi As Integer) As BitmapSource
Using bitmap As Bitmap = DirectCast(System.Drawing.Image.FromFile(path), Bitmap)
Dim bitmapData = bitmap.LockBits(New System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.[ReadOnly], bitmap.PixelFormat)
Dim bmSource = BitmapSource.Create(
bitmapData.Width,
bitmapData.Height, 96, 96, PixelFormats.Bgr24, Nothing,
bitmapData.Scan0,
bitmapData.Stride * bitmapData.Height,
bitmapData.Stride)
bitmap.UnlockBits(bitmapData)
Return bmSource
End Using
End Function
【问题讨论】:
-
您是否尝试过将
Using用于MemoryStream?您还将在End Using之前返回。我从未测试过,但这可能意味着它无法正常运行 -
@AFriend 你可以从 using 块返回,甚至抛出异常。总会得到妥善处理。
-
在调试器中单步执行,看看哪一行给出了 OOM 异常
-
@KScandrett 它在上面的源代码中显示为评论
-
如果这是 WPF,您可能需要添加该标签;否则你为什么用
System.Windows.Media?
标签: wpf vb.net image printing dpi