VB.NET - 创建图像 - 调整大小但添加背景以保留空间

时间:2012-09-16 19:51:37

标签: vb.net image gdi system.drawing system.drawing.imaging

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

我认为最简单的方法是创建一个我所需尺寸的新图像。设置背景颜色&然后添加&将图像置于此背景的顶部。

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

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

从这一点来说,我对如何完成这个过程感到有些迷茫,所需要的只是将一个图像添加到Bitmap&中心。

任何想法都会很有意义

3 个答案:

答案 0 :(得分:2)

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

grap.Clear(Drawing.Color.Black)

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

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

Graphics pic = this.CreateGraphics();
pic.Clear(Color.Black);
pic.DrawImage(img, new Point(center));

答案 1 :(得分:0)

结束使用:

' 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))

答案 2 :(得分:0)

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

是有用的