Rust-Gnuplot-将PNG作为字节保存在内存中



我正在尝试设置一个简单的activx web服务器,它有一个名为plot的端点。它本质上只是消耗一些数据,用gnuplot绘制数据,并返回生成的PNG的字节数。问题是,正如你在代码中看到的那样,我还没有找到一种在内存中完成这一切的方法,这意味着我必须将文件持久化到磁盘上,将其重新打开到读取器中,然后发送回响应。根据并发级别的不同,我将开始获取{ code: 24, kind: Other, message: "Too many open files" }消息。

有人知道我会怎么做吗?这样整个过程都会在记忆中完成?我正在使用:

actix-web = "3"
gnuplot = "0.0.37"
image = "0.23.12"

任何帮助都将不胜感激,这里是代码:

use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};
use gnuplot::{AxesCommon, Color, Figure, LineWidth};
use image::io::Reader;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::any::type_name;
use std::collections::HashMap;
use std::fs;
#[post("/")]
async fn plot(req_body: web::Json<HashMap<String, Vec<f64>>>) -> impl Responder {
let data = req_body.get("data").unwrap();
let mut fg = Figure::new();
let fid: String = thread_rng().sample_iter(&Alphanumeric).take(10).collect();
let fname: String = format!("./{fid}.png", fid = fid);
fg.set_terminal("pngcairo", &fname);
let ax = fg.axes2d();
ax.set_border(false, &[], &[]);
ax.set_pos(0.0, 0.0);
ax.set_x_ticks(None, &[], &[]);
ax.set_y_ticks(None, &[], &[]);
let x: Vec<usize> = (1..data.len()).collect();
ax.lines(&x, data, &[LineWidth(4.0), Color("black")]);
fg.set_post_commands("unset output").show();
let image = Reader::open(&fname).unwrap().decode().unwrap();
let mut bytes: Vec<u8> = Vec::new();
image.write_to(&mut bytes, image::ImageOutputFormat::Png);
fs::remove_file(fname);
HttpResponse::Ok().body(bytes)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(plot))
.bind("127.0.0.1:8080")?
.run()
.await
}

为了避免创建文件,您可以按照Akihito KIRISAKI所描述的操作。您可以通过调用set_terminal()来实现这一点,但您传递的不是文件名,而是一个空字符串。然后在stdin中创建一个Commandecho()

use std::process::{Command, Stdio};
#[post("/")]
async fn plot(req_body: web::Json<HashMap<String, Vec<f64>>>) -> impl Responder {
...
fg.set_terminal("pngcairo", "");
...
fg.set_post_commands("unset output");
let mut child = Command::new("gnuplot")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("expected gnuplot");
let mut stdin = child.stdin.take().expect("expected stdin");
fg.echo(&mut stdin);
// Drop `stdin` such that it is flused and closed,
// otherwise some programs might block until stdin
// is closed.
drop(stdin);
let output = child.wait_with_output().unwrap();
let png_image_data = output.stdout;
HttpResponse::Ok().body(png_image_data)
}

您还需要删除对show()的调用。

Crate gnuplot可能没有这样的功能。但幸运的是,gnuplot可以使用set term pngset output向stdout输出字节的图像。使用std::process::Command直接运行gnuplot,可以将输出存储到内存中。

最新更新