Use libwebp-sys crate directly.

This commit is contained in:
Kavin
2023-07-11 02:09:14 +01:00
parent 313acc9ce0
commit 043cc36dfd
3 changed files with 73 additions and 64 deletions
+18 -7
View File
@@ -1,9 +1,9 @@
use std::env;
use std::error::Error;
use actix_web::{App, HttpRequest, HttpResponse, HttpResponseBuilder, HttpServer, web};
use actix_web::http::Method;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpResponseBuilder, HttpServer};
use image::EncodableLayout;
use libwebp_sys::{WebPEncodeRGB, WebPFree};
use mimalloc::MiMalloc;
use once_cell::sync::Lazy;
use qstring::QString;
@@ -28,8 +28,8 @@ async fn main() -> std::io::Result<()> {
let bind = env::var("BIND").unwrap_or_else(|_| "0.0.0.0:8080".to_string());
server.bind(bind)?
}
.run()
.await
.run()
.await
}
static RE_DOMAIN: Lazy<Regex> =
@@ -204,17 +204,28 @@ async fn index(req: HttpRequest) -> Result<HttpResponse, Box<dyn Error>> {
let resp_bytes = resp.bytes().await.unwrap();
let image = image::load_from_memory(&resp_bytes).unwrap();
let width = image.width();
let height = image.height();
let encoder = webp::Encoder::from_image(&image).unwrap();
let quality = 85;
let encoded = encoder.encode(85f32);
let bytes = encoded.as_bytes().to_vec();
let data = image.as_rgb8().unwrap().as_raw();
let bytes: Vec<u8> = unsafe {
let mut out_buf = std::ptr::null_mut();
let stride = width as i32 * 3;
let len: usize = WebPEncodeRGB(data.as_ptr(), width as i32, height as i32, stride, quality as f32, &mut out_buf);
let vec = std::slice::from_raw_parts(out_buf, len).into();
WebPFree(out_buf as *mut _);
vec
};
if bytes.len() < resp_bytes.len() {
response.content_type("image/webp");
return Ok(response.body(bytes));
}
response.content_type("image/jpeg");
return Ok(response.body(resp_bytes));
}
if content_type == "application/x-mpegurl"