C# – Publish base64 converted image data

Publish base64 converted image data… here is a solution to the problem.

Publish base64 converted image data

What is the equivalent of this python code in C#.
This opens the image from the file and converts it to a base64-encoded string and sends a POST request.
Please help.

#!/usr/bin/python

import requests
import base64
import json

# Sample image file is available at http://plates.openalpr.com/ea7the.jpg
IMAGE_PATH = '/tmp/sample.jpg'
SECRET_KEY = 'sk_DEMODEMODEMODEMODEMODEMO'

with open(IMAGE_PATH, 'rb') as image_file:
    img_base64 = base64.b64encode(image_file.read())

url = 'https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&country=us&secret_key=%s' % (SECRET_KEY)
r = requests.post(url, data = img_base64)

print(json.dumps(r.json(), indent=2))

Solution

Untested, but enough to get you started.

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace image
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var bytes = File.ReadAllBytes("/tmp/sample.jpg");
            var base64 = Convert.ToBase64String(bytes);
            var secretKey = "my_key";
            var url = $"http://yoururl.com?my_key={secretKey}";

using(var client = new HttpClient())
            {
                var content = new StringContent(base64);
                var response = await client. PostAsync(url, content);
                var stringResponse = await response. Content.ReadAsStringAsync();

Console.WriteLine(stringResponse);
            }
        }
    }
}

Related Problems and Solutions