vb 获取网络图片宽与高并修改宽与高在ASP:Image控件中显示修改后的图片
时间: 2025-01-02 07:44:47 浏览: 8
在VB.NET中获取网络图片的宽度和高度,并根据需要调整尺寸后再显示在ASP.NET的`Image`控件中,可以按照以下步骤进行:
1. 首先,你需要使用`System.Net.WebClient`或者`System.Net.Http`等库下载图片文件。假设我们使用`WebClient`:
```vb
Imports System.IO
Imports System.Net
Public Function GetImageInfo(url As String) As ImageInfo
Using client As New WebClient()
Dim bytes As Byte() = client.DownloadData(url)
Return New ImageInfo With {
.Width = If(bytes.Length > 0, Image.FromStream(New MemoryStream(bytes)).Width, 0),
.Height = If(bytes.Length > 0, Image.FromStream(New MemoryStream(bytes)).Height, 0)
}
End Using
End Function
Private Class ImageInfo
Public Property Width As Integer
Public Property Height As Integer
End Class
```
在这个例子中,`GetImageInfo` 函数下载指定URL的图片数据,然后通过`Image.FromStream`获取其宽度和高度。
2. 然后,你可以根据需求缩放图片。这里以保持长宽比为例:
```vb
Function ResizeImage(url As String, newWidth As Integer, newHeight As Integer) As Image
Dim info = GetImageInfo(url)
Dim ratioX = newWidth / info.Width
Dim ratioY = newHeight / info.Height
Dim resizeRatio As Single = If(ratioX < ratioY, ratioX, ratioY)
Using client As New WebClient()
Dim bytes = client.DownloadData(url)
Dim resizedBytes As Byte()
Using memoryStream = New MemoryStream(bytes)
Using image = Image.FromStream(memoryStream)
Dim newSize As SizeF = New SizeF(newWidth, newHeight)
Dim newSizeAsInt As Size = New Size((image.Width * resizeRatio).Ceiling, (image.Height * resizeRatio).Ceiling)
Dim graphics = Graphics.FromImage(image)
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic
graphics.DrawImage(image, 0, 0, newSizeAsInt.Width, newSizeAsInt.Height)
resizedBytes = New Bitmap(graphics, newSize).ToByteArray()
End Using
End Using
Return Image.FromStream(New MemoryStream(resizedBytes))
End Using
End Function
' 使用方法:
Dim modifiedImage = ResizeImage("yourImageUrl", NewWidth, NewHeight)
ImageControl.ImageUrl = "~/YourPath/" & "modifiedImage.png" ' 将图片赋值给Image控件
```
这会下载图片,根据新的宽度和高度比例缩放图片,然后返回一个新大小的`Image`对象。
阅读全文