图像不适合图片框



我有一个winforms程序,可以扫描文档并将其保存到文件中,然后它会打开另一个表单并将图像的裁剪部分加载到图片框中,但图像没有填充图片框。

执行此操作的代码如下所示:

Public Function Crop() As Image
' Function to rotate and crop the scanned image to speed up barcode reading
Dim Mystream As New FileStream(TempRoot & StrFileName & Exten, FileMode.Open)
Dim bitmap1 As New Bitmap(Mystream)
imageAttr1.SetGamma(2.2F)
' Rotates and crops the scanned document
Try
If bitmap1 IsNot Nothing Then
bitmap1.RotateFlip(RotateFlipType.Rotate270FlipNone)
End If
cropX = 1500
cropY = 200
cropWidth = 1100
cropHeight = 550
' Sets a rectangle to display the area of the source image
rect = New Rectangle(cropX, cropY, cropWidth, cropHeight)
' Create a new bitmap with the width and height values specified by cropWidth and cropHeight.
cropBitmap = New Bitmap(cropWidth, cropHeight)
' Creates a new Graphics object that will draw on the cropBitmap
g = Graphics.FromImage(cropBitmap)
' Draws the portion of the image that you supplied cropping values for.
g.DrawImage(bitmap1, 0, 0, rect, GraphicsUnit.Pixel)
g.DrawImage(cropBitmap, rect, 0, 0, OKTickets.ImgTicket.Width, OKTickets.ImgTicket.Height, GraphicsUnit.Pixel, imageAttr1)
Catch ex As System.IO.FileNotFoundException
MessageBox.Show("There was an error. Check the path to the bitmap.")
End Try
Mystream.Close()
Return cropBitmap
End Function

我在表格上有一个标签,显示图像的宽度和高度以及图片框的宽度和高度。

图片框的大小为宽度= 1100,高度= 550。

图像显示相同的大小,但它只填充图片框的左上角四分之一。

我尝试将图片框大小模式设置为所有设置,但它对图像根本没有影响。

谁能看出为什么它没有填满图片框?

我相信您遇到了缩放问题。
您指示已扫描源图像。 图像很可能是以高分辨率扫描的。 创建新Bitmap时,其默认分辨率为 96 x 96。

从您正在使用的 DrawImage 方法的Remarks部分。

图像存储像素宽度值和水平分辨率值(每英寸点数(。图像的物理宽度(以英寸为单位(是像素宽度除以水平分辨率。例如,像素宽度为 360、水平分辨率为每英寸 72 点的图像的物理宽度为 5 英寸。类似的备注也适用于像素高度和物理高度。

此方法使用其物理大小绘制图像的一部分,因此 图像部分将具有正确的大小(以英寸为单位(,无论 显示设备的分辨率(每英寸点数(。例如 假设图像部分的像素宽度为 216,水平 分辨率为每英寸 72 点。如果调用此方法来绘制 分辨率为每英寸 96 点的设备上的图像部分, 渲染图像部分的像素宽度将为 (216/72(*96 = 288.

您有两个选项来解决此问题。

  1. 您可以设置cropBitmap的分辨率以匹配源图像。

    cropBitmap.SetResolution(bitmap1.水平分辨率,位图1。垂直分辨率(

  2. 使用 DrawImageUnscaled 方法。

    g.DrawImageUnscaled(bitmap1, -rect.左,-直。顶部, 0, 0(

最新更新