data_faking/data/image/
uri.rs1use wasm_bindgen::prelude::*;
2use base64::{engine::general_purpose::STANDARD, Engine};
3use crate::{locales::en::misc::colors, utils::seeder};
4
5const FORMAT_BASE: &str = "data:image/svg+xml;";
6
7pub fn image_uri(props: Option<URI_Properties>) -> String {
9 let mut height = seeder::gen_range(1..4000);
10 let mut width = seeder::gen_range(1..4000);
11 let mut color = colors::hex_color();
12 let mut svg_type = ENCODE_FORMAT[seeder::gen_range(0..=1)];
13
14 if props.is_some() {
15 let p = props.unwrap();
16 if p.height.is_some() {
17 let h = p.height.unwrap();
18 height = if h < 1 {
19 1
20 } else if h >= 4000 {
21 3999
22 } else {
23 h
24 }
25 }
26
27 if p.width.is_some() {
28 let w = p.width.unwrap();
29 width = if w < 1 {
30 1
31 } else if w >= 4000 {
32 3999
33 } else {
34 w
35 }
36 }
37
38 if p.color.is_some() {
39 color = p.color.unwrap().to_string();
40 }
41
42 if p.svg_type.is_some() {
43 svg_type = p.svg_type.unwrap();
44 }
45 }
46
47 let half_height = height / 2;
48 let half_width = width / 2;
49
50 let tag_svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" baseProfile="full" width="{}" height="{}">"#, width, height);
51 let tag_rect = format!(r#"<rect width="100%" height="100%" fill="{}"/>"#, color);
52 let tag_text_outer = format!(r#"<text x="{}" y="{}" font-size="20" alignment-baseline="middle" text-anchor="middle" fill="white">"#, half_width, half_height);
53 let tag_text_inner = format!("{}x{}", width, height);
54
55 let svg = concat_string!(tag_svg, tag_rect, tag_text_outer, tag_text_inner, "</text>", "</svg>");
56 if svg_type == "svg-uri" {
57 return to_svg_encode(svg);
58 }
59 return to_base64_encode(svg);
60}
61
62fn to_base64_encode(svg: String) -> String {
63 let encoded_text = STANDARD.encode(svg);
64 format!("{}base64,{}", FORMAT_BASE, encoded_text)
65}
66
67fn to_svg_encode(svg: String) -> String {
68 let encoded_text: String = url::form_urlencoded::byte_serialize(svg.as_bytes()).collect();
69 format!("{}charset=UTF-8,{}", FORMAT_BASE, encoded_text)
70}
71
72#[derive(Clone)]
74pub struct URI_Properties {
75 pub height: Option<u16>,
76 pub width: Option<u16>,
77 pub color: Option<&'static str>,
78 pub svg_type: Option<&'static str>,
79}
80
81static ENCODE_FORMAT: [&'static str; 2] = [
82 "svg-uri",
83 "svg-base64"
84];
85
86