using KdanCommon.GoogleCloud.Data.Vision; using KdanCommon.Helpers; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Globalization; using Windows.Storage; using Windows.System; namespace KdanCommon.GoogleCloud { public class GoogleCloud { public static string VisionDomain = "https://vision.googleapis.com"; private Uri _visionImagesUri = null; private HttpClient _httpClient = null; private string _key = null; public GoogleCloud(string key) { _key = key; _httpClient = new HttpClient(); _visionImagesUri = new Uri($"{VisionDomain}/v1/images:annotate?key={_key}"); } ~GoogleCloud() { _httpClient.Dispose(); } // Document : https://cloud.google.com/vision/docs/reference/rest/v1/images/annotate // Image files sent to the Vision API should not exceed 20MB. // Files exceeding 20MB generate an error. // The Vision API does not resize files of this size. Reducing your file size can significantly improve throughput; // however, be careful not to reduce image quality in the process. // Note that the Vision API imposes a 10MB JSON request size limit; // larger files should be hosted on Cloud Storage or on the web, rather than being passed as base64-encoded content in the JSON itself. public async Task GetVisionImages(List images) { ImagesResponse response = null; var base64Contents = new List(); foreach (var image in images) { var base64Content = await Base64Helper.StorageFileToBase64(image); base64Contents.Add(base64Content); } var imagesRequest = new ImgesRequest(base64Contents); string requestJsonStr = JsonConvert.SerializeObject(imagesRequest); var content = new StringContent(requestJsonStr, System.Text.Encoding.UTF8, "application/json"); var result = await _httpClient.PostAsync(_visionImagesUri, content); if (result.StatusCode == System.Net.HttpStatusCode.OK) { var jsonString = await result.Content.ReadAsStringAsync(); response = JsonTool.DeserializeJSON(jsonString); } return response; } } }