1

我正在尝试将图像调整为特定尺寸,但如果图像小于我选择的尺寸,我根本不想拉伸图像。相反,我想在未使用的图像区域周围添加黑色背景。

我认为最简单的方法是创建一个我想要的尺寸的新图像并设置背景颜色,然后将图像添加并居中于该背景之上。

我使用以下方法创建了位图:

Dim bmp As New Drawing.Bitmap(500, 500)
Dim grap As Drawing.Graphics = Drawing.Graphics.FromImage(bmp)
grap.Clear(Drawing.Color.Black)

从这一点开始,我对如何完成该过程有点迷茫,所需要的只是将图像添加到位图和中心。

任何想法都会非常感激

4

3 回答 3

2

我没有对此进行测试,但看起来你已经得到了你想要的,但是:

grap.Clear(Drawing.Color.Black)

肯定会将整个图形抹回黑色。

尝试在绘制图像之前进行清除:

Graphics pic = this.CreateGraphics();
pic.Clear(Color.Black);
pic.DrawImage(img, new Point(center));
于 2012-09-16T20:24:46.670 回答
1

最终使用:

' Load Image
Dim FilePath As String = "testimage.jpg"
Dim OriginalImage As New Bitmap(FilePath)

' Resize Image While Maintaining Aspect Ratio
Dim aspectRatio As Double
Dim newHeight As Integer
Dim newWidth As Integer
Dim maxWidth As Integer = 500
Dim maxHeight As Integer = 500

' Calculate Size
If OriginalImage.Width > maxWidth Or OriginalImage.Height > maxHeight Then
    If OriginalImage.Width >= OriginalImage.Height Then ' image is wider than tall
        newWidth = maxWidth
        aspectRatio = OriginalImage.Width / maxWidth
        newHeight = CInt(OriginalImage.Height / aspectRatio)
    Else ' image is taller than wide
        newHeight = maxHeight
        aspectRatio = OriginalImage.Height / maxHeight
        newWidth = CInt(OriginalImage.Width / aspectRatio)
    End If
Else ' if image is not larger than max then increase size
    If OriginalImage.Width > OriginalImage.Height Then
        newWidth = maxWidth
        aspectRatio = OriginalImage.Width / maxWidth
        newHeight = CInt(OriginalImage.Height / aspectRatio)
    Else
        newHeight = maxHeight
        aspectRatio = OriginalImage.Height / maxHeight
        newWidth = CInt(OriginalImage.Width / aspectRatio)
    End If

    ' Below keeps original height & width instead of resizing to fit new height / width
    ' newWidth = OriginalImage.Width
    ' newHeight = OriginalImage.Height
End If

Dim newImg As New Bitmap(OriginalImage, CInt(newWidth), CInt(newHeight)) '' blank canvas
' Create New Bitmap
Dim bmp As New Drawing.Bitmap(500, 500)
Dim grap As Drawing.Graphics = Drawing.Graphics.FromImage(bmp)
grap.Clear(Drawing.Color.Black)
Dim g As Graphics = Graphics.FromImage(bmp)

' Calculate Points To Insert Resized Image
Dim InsertX As Integer
Dim InsertY As Integer

' Calculate Y Axis Point
If newImg.Height >= 500 Then
    InsertY = 0
Else
    InsertY = CInt(((500 - newImg.Height) / 2))
End If

' Calculate X Axis Point
If newImg.Width >= 500 Then
    InsertX = 0
Else
    InsertX = CInt(((500 - newImg.Width) / 2))
End If

' Add Resized Image To Canvas
g.DrawImage(newImg, New Point(InsertX, InsertY))
于 2012-09-17T12:10:12.900 回答
0

通过仅使用较大轴的比率,您可能会在另一个比率迫使您超过另一个轴的情况下失败。即 1400x1000 ->(我想适应 300x200)-> 但只有 1400/300 比率(4.6),结果将是 300x214。我认为检查这两个比率并继续使用更大的比率会很有用

于 2015-10-17T21:19:42.020 回答