I wrote this script for you:
$img = Get-Clipboard -Format Image
If (-not $img) {Throw 'No image on the clipboard'}
$ms = New-Object System.IO.MemoryStream
$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
$ms.Position = 0
Add-Type -AssemblyName System.Net.Http
$httpClientHandler = New-Object System.Net.Http.HttpClientHandler
$httpClient = New-Object System.Net.Http.HttpClient $httpClientHandler
$contentDispositionHeaderValue = New-Object System.Net.Http.Headers.ContentDispositionHeaderValue "form-data"
$contentDispositionHeaderValue.Name = "file"
$contentDispositionHeaderValue.FileName = 'image.png'
$streamContent = New-Object System.Net.Http.StreamContent $ms
$streamContent.Headers.ContentDisposition = $contentDispositionHeaderValue
$streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue 'image/png'
$content = New-Object System.Net.Http.MultipartFormDataContent
$content.Add($streamContent)
$response = $httpClient.PostAsync('https://stackoverflow.com/upload/image?https=true', $content).Result
$response.Content.ReadAsStringAsync().Result -match '"(.*)"' | Out-Null
"![]($($matches[1]))"
First, it converts the image on the clipboard to PNG. Then it takes advantage of some .NET web utility classes to get the multipart/form-data
structure set up just right - this section is adapted from Mario Majčica's blog post. Once that's all finagled, it makes the POST request. Finally, it uses regex to parse the small resulting HTML document to extract the URL of the newly uploaded image, which it prints to the console. If you'd like to copy the Markdown fragment directly to the clipboard, tack on | scb
to the last line.
To run the script, save it as a .ps1
file, e.g. seimage.ps1
. If you haven't already, follow the instructions in the Enabling Scripts section of the PowerShell tag wiki. Then you can open a PowerShell prompt in the containing folder and execute it:
.\seimage.ps1
invoke-restmethod
orinvoke-webrequest
, see this answer for an example stackoverflow.com/a/36269506/1123692