GoogleCloud.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using KdanCommon.GoogleCloud.Data.Vision;
  2. using KdanCommon.Helpers;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Windows.Globalization;
  12. using Windows.Storage;
  13. using Windows.System;
  14. namespace KdanCommon.GoogleCloud
  15. {
  16. public class GoogleCloud
  17. {
  18. public static string VisionDomain = "https://vision.googleapis.com";
  19. private Uri _visionImagesUri = null;
  20. private HttpClient _httpClient = null;
  21. private string _key = null;
  22. public GoogleCloud(string key)
  23. {
  24. _key = key;
  25. _httpClient = new HttpClient();
  26. _visionImagesUri = new Uri($"{VisionDomain}/v1/images:annotate?key={_key}");
  27. }
  28. ~GoogleCloud()
  29. {
  30. _httpClient.Dispose();
  31. }
  32. // Document : https://cloud.google.com/vision/docs/reference/rest/v1/images/annotate
  33. // Image files sent to the Vision API should not exceed 20MB.
  34. // Files exceeding 20MB generate an error.
  35. // The Vision API does not resize files of this size. Reducing your file size can significantly improve throughput;
  36. // however, be careful not to reduce image quality in the process.
  37. // Note that the Vision API imposes a 10MB JSON request size limit;
  38. // larger files should be hosted on Cloud Storage or on the web, rather than being passed as base64-encoded content in the JSON itself.
  39. public async Task<ImagesResponse> GetVisionImages(List<StorageFile> images)
  40. {
  41. ImagesResponse response = null;
  42. var base64Contents = new List<string>();
  43. foreach (var image in images)
  44. {
  45. var base64Content = await Base64Helper.StorageFileToBase64(image);
  46. base64Contents.Add(base64Content);
  47. }
  48. var imagesRequest = new ImgesRequest(base64Contents);
  49. string requestJsonStr = JsonConvert.SerializeObject(imagesRequest);
  50. var content = new StringContent(requestJsonStr, System.Text.Encoding.UTF8, "application/json");
  51. var result = await _httpClient.PostAsync(_visionImagesUri, content);
  52. if (result.StatusCode == System.Net.HttpStatusCode.OK)
  53. {
  54. var jsonString = await result.Content.ReadAsStringAsync();
  55. response = JsonTool.DeserializeJSON<ImagesResponse>(jsonString);
  56. }
  57. return response;
  58. }
  59. }
  60. }