Forum Discussion
x315307
Apr 10, 2025Copper Contributor
Extract image from http response and save it to local folder
Below excel macro code triggers provider to generate an image in .png format:
Sub GetImg ()
Dim MyRequest As Object
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"https://<provider addr>?text=<instruction for image>"
' Send Request.
MyRequest.Send
'And we get this response with the .png image
MsgBox MyRequest.ResponseText
End Sub
The image is there, content type is image/png.
How can I extract it from the body and save the image to a local folder e.g. to the same folder where the .xlsm excel file is.
Sub GetImg() Dim MyRequest As Object Dim ByteArray() As Byte Dim FileNum As Integer Dim FilePath As String Dim FileName As String ' Create the request Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1") MyRequest.Open "GET", "https://<provider addr>?text=<instruction for image>", False MyRequest.Send ' Check if the content type is image/png If InStr(1, MyRequest.GetResponseHeader("Content-Type"), "image/png", vbTextCompare) > 0 Then ' Get binary response body ByteArray = MyRequest.ResponseBody ' Create file path in the same folder as the workbook FileName = "downloaded_image_" & Format(Now, "yyyymmdd_hhnnss") & ".png" FilePath = ThisWorkbook.Path & "\" & FileName ' Save binary data to file FileNum = FreeFile Open FilePath For Binary As #FileNum Put #FileNum, , ByteArray Close #FileNum MsgBox "Image saved to: " & FilePath Else MsgBox "Response was not an image. Content-Type: " & MyRequest.GetResponseHeader("Content-Type") End If End SubSince your response is a binary .png image, and you're getting it via a WinHttpRequest, you need to work with the binary response body, not ResponseText.
Hope this helps you.
1 Reply
- NikolinoDEPlatinum Contributor
Sub GetImg() Dim MyRequest As Object Dim ByteArray() As Byte Dim FileNum As Integer Dim FilePath As String Dim FileName As String ' Create the request Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1") MyRequest.Open "GET", "https://<provider addr>?text=<instruction for image>", False MyRequest.Send ' Check if the content type is image/png If InStr(1, MyRequest.GetResponseHeader("Content-Type"), "image/png", vbTextCompare) > 0 Then ' Get binary response body ByteArray = MyRequest.ResponseBody ' Create file path in the same folder as the workbook FileName = "downloaded_image_" & Format(Now, "yyyymmdd_hhnnss") & ".png" FilePath = ThisWorkbook.Path & "\" & FileName ' Save binary data to file FileNum = FreeFile Open FilePath For Binary As #FileNum Put #FileNum, , ByteArray Close #FileNum MsgBox "Image saved to: " & FilePath Else MsgBox "Response was not an image. Content-Type: " & MyRequest.GetResponseHeader("Content-Type") End If End SubSince your response is a binary .png image, and you're getting it via a WinHttpRequest, you need to work with the binary response body, not ResponseText.
Hope this helps you.