microsoft_cognitive_computer_vision/data_types/
image_input.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone)]
4pub struct ImageInput {
5    inner: ImageInputInner,
6}
7
8#[derive(Debug, Clone)]
9enum ImageInputInner {
10    Url(String),
11    Raw(Vec<u8>),
12}
13
14impl ImageInput {
15    pub fn with_url(url: impl AsRef<str>) -> Result<Self, String> {
16        let url = url.as_ref();
17
18        // TODO, check url schema
19
20        Ok(Self {
21            inner: ImageInputInner::Url(url.to_owned()),
22        })
23    }
24
25    pub fn with_raw(bytes: impl AsRef<[u8]>) -> Result<Self, String> {
26        let bytes = bytes.as_ref();
27
28        // TODO, check
29        /*
30        Supported image formats: JPEG, PNG, GIF, BMP.
31        Image file size must be less than 4MB.
32        Image dimensions should be greater than 50 x 50.
33        */
34
35        Ok(Self {
36            inner: ImageInputInner::Raw(bytes.to_owned()),
37        })
38    }
39
40    pub fn to_request_body_and_content_type(&self) -> Result<(Vec<u8>, &'static str), String> {
41        match &self.inner {
42            ImageInputInner::Url(url) => {
43                let body = ImageInputRequestJsonBody {
44                    url: url.to_owned(),
45                };
46                let body =
47                    serde_json::to_vec(&body).map_err(|err| format!("ser failed, err: {}", err))?;
48                Ok((body, "application/json"))
49            }
50            ImageInputInner::Raw(bytes) => Ok((bytes.to_owned(), "application/octet-stream")),
51        }
52    }
53}
54
55#[derive(Serialize, Deserialize, Debug, Clone)]
56pub struct ImageInputRequestJsonBody {
57    pub url: String,
58}