【发布时间】:2022-01-23 14:57:30
【问题描述】:
我想将图像调整为最大宽度和高度,然后裁剪它。 调整大小有效。但是裁剪code I found here 没有。
我自己现有的代码使用字节数组,所以我需要使用它。
所以下面的代码会调整大小,不会裁剪,并会保存新图像。我在裁剪方面做错了什么?
Dim imgNewWidth, imgNewHeight As Integer
Dim _originalThumbWidth As Integer = 900
Dim _originalThumbHeight As Integer = 900
Dim imageURL As String = "https://med.stanford.edu/news/all-news/2021/09/cat-fur-color-patterns/_jcr_content/main/image.img.780.high.jpg/cat_by-Kateryna-T-Unsplash.jpg"
Dim localImagePath As String = Server.MapPath("images\_tmp\") + "CROPPED.jpg"
ResizeAndSaveFast(_originalThumbWidth, _originalThumbHeight, imageURL, localImagePath, "", "", imgNewWidth, imgNewHeight)
Private Function ResizeAndSaveFast(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal imageURL As String, ByVal saveToPath As String, ByVal userName As String, ByVal password As String,
ByRef imgNewWidth As Integer, ByRef imgNewHeight As Integer) As Boolean
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse
Dim memStream As New MemoryStream
Try
imgResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
streamPhoto.CopyTo(memStream)
memStream.Position = 0
Catch ex As Exception
Return False
End Try
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim newWidth, newHeight As Integer
Dim scaleFactor As Double
newWidth = bfPhoto.PixelWidth
newHeight = bfPhoto.PixelHeight
imgNewWidth = newWidth
imgNewHeight = newHeight
If bfPhoto.PixelWidth > maxWidth Or bfPhoto.PixelHeight > maxHeight Then
If bfPhoto.PixelWidth > maxWidth Then
scaleFactor = maxWidth / bfPhoto.PixelWidth
newWidth = CInt(Math.Round(bfPhoto.PixelWidth * scaleFactor, 0))
newHeight = CInt(Math.Round(bfPhoto.PixelHeight * scaleFactor, 0))
End If
If newHeight > maxHeight Then
scaleFactor = maxHeight / newHeight
newWidth = CInt(Math.Round(newWidth * scaleFactor, 0))
newHeight = CInt(Math.Round(newHeight * scaleFactor, 0))
End If
End If
imgNewWidth = newWidth
imgNewHeight = newHeight
Dim bfResize As BitmapFrame = FastResize(bfPhoto, newWidth, newHeight)
Dim baResize As Byte() = ToByteArray(bfResize)
Dim bmp As System.Drawing.Bitmap = imageFunctions.ConvertByteArrayToBitmap(baResize)
Dim CropArea As Rectangle = New Rectangle(100, 100, bmp.Width - 100, bmp.Height - 100)
Dim bm As Bitmap = New Bitmap(CropArea.Width, CropArea.Height)
Using g As Graphics = Graphics.FromImage(bm)
g.DrawImage(bm, New Rectangle(0, 0, bm.Width, bm.Height),
CropArea,
GraphicsUnit.Pixel)
End Using
bm.Save(saveToPath, ImageFormat.Jpeg)
Return True
End Function
【问题讨论】:
-
快速浏览一下,我认为您可以将“g.DrawImage(bm ....”)更改为“g.DrawImage(bmp ....”)(?)您没有使用bmp 变量是您要裁剪的位图(我假设)。我认为发布的答案是正确的,但不完整。
-
谢谢。当我将代码更改为
Using g As Graphics = Graphics.FromImage(bmp)时,结果只是一张全黑的图像......
标签: arrays asp.net vb.net bitmap crop