Hi, I'm trying to create a function to print multiple lines of text to an image. I'm using the imageproc crate to accomplish this, I have done the same thing in Python using Python's with
keyword, but Rust doesn't have an equivalent.
I'm using a for loop and the textwrap crate to make sure the lines of text will always fit into the image. Text wrap separates the text into sections and putting them into a Vector. I use this vector to iterate over the lines and print them out separately on the image. The function is below:
fn draw_fact_text(fact: &str, color: image::Rgba<u8>, fact_image: &str, mut x: i32, y: i32) {
// Load image
let fact_img = image::open(fact_image).unwrap();
// Load font data
let font_bytes = include_bytes!("../fonts/sans_rounded.ttf");
let font = Font::try_from_bytes(font_bytes).unwrap();
let wrapped_fact = textwrap::wrap(fact, 30);
for line in wrapped_fact {
let img = draw_text(
&fact_img,
color,
x,
y,
Scale { x: 30.0, y: 30.0 },
&font,
&line,
);
x = x + 25;
}
match img.save("test.jpg") {
Ok(_) => println!("Success!"),
Err(e) => println!("Failed: {}", e),
}
}
My problem is that img
goes out of scope after the for loop and I don't know how to save the new image, I'm referencing my Python version of this function to follow the same logic but its not working for me because Rust is so different.
Any advice and help would be appreciated, thanks