Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Saving Image Response To A PNG File In Mac #494

Open
1504168 opened this issue Feb 16, 2024 · 0 comments
Open

Saving Image Response To A PNG File In Mac #494

1504168 opened this issue Feb 16, 2024 · 0 comments

Comments

@1504168
Copy link

1504168 commented Feb 16, 2024

I am trying to call an API get the image response and save it back to a PNG file. It is working fine in Windows, but I can't make it work on Mac.

Here is my sample code:

Option Explicit

Public Sub Test()
    
    Dim Response As WebResponse
    Dim Clinet As New WebClient
    Const URL As String = "https://kayaconnect.org/pluginfile.php/383257/course/overviewfiles/excel.png"
    Clinet.BaseURL = URL
    
    Dim Req As New WebRequest
    Req.ContentType = "image/png"
    Req.Method = HttpGet
    
    Set Response = Clinet.Execute(Req)
    SaveResponseBodyAsImage Response.Body, ThisWorkbook.Path & Application.PathSeparator & "Output.png"
    If IsMacOS() Then
        Sheet1.Range("A2:A1048576").ClearContents
        Sheet1.Range("A2").Resize(UBound(Response.Body)).Value = Application.WorksheetFunction.Transpose(Response.Body)
    Else
        Sheet1.Range("B2:B1048576").ClearContents
        Sheet1.Range("B2").Resize(UBound(Response.Body)).Value = Application.WorksheetFunction.Transpose(Response.Body)
    End If
    MsgBox "Done."
    
End Sub

Private Sub SaveResponseBodyAsImage(ByRef ResponseBody() As Byte, FilePath As String)
    
    If Dir(FilePath) <> vbNullString Then
        Kill FilePath
    End If
    
    Dim FileNo As Integer
    FileNo = FreeFile
    Open FilePath For Binary Access Write As #FileNo
    Put #FileNo, 1, ResponseBody
    Close #FileNo
    
End Sub

Public Function IsMacOS() As Boolean
        
    '@Description("This Short function will let you know if the current OS is MAC or Windows.")
    '@Dependency("No Dependency")
    '@ExampleCall : IsMacOS
    '@Date : 13 October 2021

    Const WindowsIdentifierPattern As String = "*Windows*"
    IsMacOS = Not (Application.OperatingSystem Like WindowsIdentifierPattern)

End Function

Just place this code in a new module in the VBA - Web -Blank.xlsm file and then we can test it out.

I am not using ADODB.Stream as I need it to work in both Win and Mac.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant