Script to use Google Image Search with local image as input

前端 未结 3 603
时光取名叫无心
时光取名叫无心 2020-12-24 15:58

I\'m looking for a batch or Powershell script to search for similar images on Google images using a local image as input.

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 15:58

    function Get-GoogleImageSearchUrl
    {
        param(
            [Parameter(Mandatory = $true)]
            [ValidateScript({ Test-Path $_ })]
            [string] $ImagePath
        )
    
        # extract the image file name, without path
        $fileName = Split-Path $imagePath -Leaf
    
        # the request body has some boilerplate before the raw image bytes (part1) and some after (part2)
        #   note that $filename is included in part1
        $part1 = @"
    --7dd2db3297c2202
    Content-Disposition: form-data; name="encoded_image"; filename="$fileName"
    Content-Type: application/octet-stream`r`n`r`n
    "@
        $part2 = @"
    `r`n--7dd2db3297c2202--`r`n
    "@
    
        # grab the raw bytes composing the image file
        $imageBytes = [Io.File]::ReadAllBytes($imagePath)
    
        # the request body should sandwich the image bytes between the 2 boilerplate blocks
        $encoding = New-Object Text.ASCIIEncoding
        $data = $encoding.GetBytes($part1) + $imageBytes + $encoding.GetBytes($part2)
    
        # create the HTTP request, populate headers
        $request = [Net.HttpWebRequest] ([Net.HttpWebRequest]::Create('http://images.google.com/searchbyimage/upload'))
        $request.Method = "POST"
        $request.ContentType = 'multipart/form-data; boundary=7dd2db3297c2202'  # must match the delimiter in the body, above
    
        # don't automatically redirect to the results page, just take the response which points to it
        $request.AllowAutoredirect = $false
    
        # populate the request body
        $stream = $request.GetRequestStream()
        $stream.Write($data, 0, $data.Length)
        $stream.Close()        
    
        # get response stream, which should contain a 302 redirect to the results page
        $respStream = $request.GetResponse().GetResponseStream()
    
        # pluck out the results page link that you would otherwise be redirected to
        (New-Object Io.StreamReader $respStream).ReadToEnd() -match 'HREF\="([^"]+)"' | Out-Null
        $matches[1]
    }
    $url = Get-GoogleImageSearchUrl 'C:\somepic.jpg'
    Start-Process $url
    

提交回复
热议问题