-
I'm trying to return an use color_processing::Color;
use image::{EncodableLayout, ImageBuffer, Rgba};
use poem::{http::StatusCode, Result};
use poem_openapi::{param::Path, payload::Binary, ApiResponse, OpenApi};
#[derive(ApiResponse)]
enum ImageResponse {
#[oai(content_type = "image/png", status = 200)]
Png(Binary<Vec<u8>>),
}
pub struct Route;
#[OpenApi]
impl Route {
/// Generate a solid color image
#[oai(path = "/hex/generate/:color/:height/:width", method = "get")]
async fn hex(
&self,
color: Path<String>,
height: Path<u32>,
width: Path<u32>,
) -> Result<ImageResponse> {
let Ok(color) = color.0.parse::<Color>() else {
return Err(poem::Error::from_status(StatusCode::BAD_REQUEST))
};
let rgba = Rgba([color.red, color.green, color.blue, color.alpha]);
let image = ImageBuffer::from_pixel(width.0, height.0, rgba);
let bytes = image.as_bytes().to_owned();
Ok(ImageResponse::Png(Binary(bytes)))
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
sunli829
Dec 29, 2022
Replies: 2 comments 2 replies
-
I tried it and it works fine, what error are you getting here? |
Beta Was this translation helpful? Give feedback.
1 reply
-
You must be encoding the image to the PNG format #[oai(path = "/hex/generate/:color/:height/:width", method = "get")]
async fn hex(
&self,
color: Path<String>,
height: Path<u32>,
width: Path<u32>,
) -> Result<ImageResponse> {
let Ok(color) = color.0.parse::<Color>() else {
return Err(poem::Error::from_status(StatusCode::BAD_REQUEST))
};
let rgba = Rgba([color.red, color.green, color.blue, color.alpha]);
let image = ImageBuffer::from_pixel(width.0, height.0, rgba);
let mut png_bytes = Vec::new();
image
.write_to(&mut std::io::Cursor::new(&mut png_bytes), ImageFormat::Png)
.map_err(InternalServerError)?;
Ok(ImageResponse::Png(Binary(png_bytes)))
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ShayBox
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You must be encoding the image to the PNG format