Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szUrl As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Dim szpath As String
Private Sub Command1_Click()
Dim strUrl As String
Dim strImage As String
Dim szImageName As String
Dim count As Long
Dim szFileName As String
Dim isDownSuc As Boolean
Dim J As Long
strUrl = Trim(Text1.Text)
If Dir(App.Path & "\temp", vbDirectory) = "" Then
MkDir App.Path & "\temp"
End If
Retry:
'//取图片的API
URLDownloadToFile 0, strUrl, strImage, 0, 0
Sleep 500
DoEvents
'//重试3次,不成功则不显示
If Dir(strImage) = "" Then
If J >= 5 Then
J = 0
isDownSuc = False
Else
J = J + 1
DoEvents
GoTo Retry
End If
Else
isDownSuc = True
End If
'//判断图片类型
szImageName = strImage & "." & ProcessImageFile(strImage)
On Error Resume Next
'//重命名图片文件
Name strImage As szImageName
'//用picbox显示图片
Picture1.Picture = LoadPicture(szImageName)
DoEvents
Sleep 500
Err.Clear
End Sub
moudle中用来判断图片类型的函数:
Public Function ProcessImageFile(ImageFileName As String, Optional CharsCount As Long = 0) As String
Dim FileNumber As Integer
Dim strData As String
Dim alngBits() As Long
Dim I&, J&, K&, M&, lBit&
Dim fs, a
Dim strTemp As String
Dim lWidth&, lHeight&
Dim vntSplit As Variant
Dim bytTemp As Byte
Dim abtBit(1 To 5) As Byte
Dim strValue As String
Dim strExt As String
Dim strResult As String
Dim vntSp
On Error Resume Next
FileNumber = FreeFile ' 取得未使用的文件号。
Open ImageFileName For Binary Access Read As #FileNumber ' 创建文件名。
Get #FileNumber, , abtBit ' 输出文本至文件中。
Close #FileNumber ' 关闭文件。
If (abtBit(1) = &H23 And abtBit(2) = &H64 And abtBit(3) = &H65) Then strExt = "xbm"
If (abtBit(1) = &H47 And abtBit(2) = &H49 And abtBit(3) = &H46) Then strExt = "gif"
If (abtBit(1) = &H89 And abtBit(2) = &H50 And abtBit(3) = &H4E) Then strExt = "png"
If (abtBit(1) = &HFF And abtBit(2) = &HD8 And abtBit(3) = &HFF) Then strExt = "jpg"
If (abtBit(1) = &H42 And abtBit(2) = &H4D) Then strExt = "bmp"
Err.Clear
ProcessImageFile = strExt
End Function