Forum Discussion

x315307's avatar
x315307
Copper Contributor
Apr 10, 2025
Solved

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") MyRequ...
  • NikolinoDE's avatar
    Apr 11, 2025
    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 Sub

    Since 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.

Resources