Closed ShayBox closed 10 months ago
I figured out how to do it, by searching GitHub I found Revolt has this code
use std::io::Cursor;
use color_processing::Color;
use image::{ImageBuffer, ImageFormat, Rgba};
use rocket::response::status::BadRequest;
use rocket_okapi::{
gen::OpenApiGenerator,
okapi::openapi3::Responses,
openapi,
response::OpenApiResponderInner,
OpenApiError,
};
const MAX_SIZE: u32 = 2048;
#[derive(Responder)]
#[response(status = 200, content_type = "image/png")]
pub struct Image(Vec<u8>);
impl OpenApiResponderInner for Image {
fn responses(_gen: &mut OpenApiGenerator) -> Result<Responses, OpenApiError> {
use rocket_okapi::okapi::{
openapi3::{MediaType, RefOr, Response, SchemaObject},
schemars::{
schema::{InstanceType, SingleOrVec},
Map,
},
};
let content = Map::from([(
String::from("image/png"),
MediaType {
schema: Some(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
format: Some(String::from("binary")),
..Default::default()
}),
..Default::default()
},
)]);
let responses = Map::from([(
String::from("200"),
RefOr::Object(Response {
description: String::from("Image"),
content,
..Default::default()
}),
)]);
Ok(Responses {
responses,
..Default::default()
})
}
}
/// Generate a solid color image
///
/// # Errors
///
/// Will return `Err` if `height`/`width` are too big or `&str::parse`/`ImageBuffer::write_to` errors.
#[openapi(tag = "Misc")]
#[get("/hex/<color>/<height>/<width>")]
pub fn hex(color: &str, height: u32, width: u32) -> Result<Image, BadRequest<String>> {
if height > MAX_SIZE || width > MAX_SIZE {
let size = height.max(width);
let err = format!("{size} is larger than the maximum size ({MAX_SIZE})");
return Err(BadRequest(err));
}
let color = color.parse::<Color>().map_err(BadRequest)?;
let rgba = Rgba([color.red, color.green, color.blue, color.alpha]);
let image = ImageBuffer::from_pixel(width, height, rgba);
let mut bytes = Vec::new();
image
.write_to(&mut Cursor::new(&mut bytes), ImageFormat::Png)
.map_err(|error| {
eprintln!(" >> Error: {error}");
BadRequest(error.to_string())
})?;
Ok(Image(bytes))
}
I'm switching from Poem to Rocket and I need to respond with an
image/png
content-typePoem:
Rocket:
EDIT: I found the rocket responder, but it doesn't implement OpenApiResponder/Inner.