Text rendering via text-to-png

hello , I am using text-to-png crate to render the ascii text onto png , however for some reason if i pass text directly like "hello" , it creates img nicely but if i pass the ascii text generated from image and try to render it on image, it does not works .

ascii text generated is completely fine so not sure why it's not being rendered properly . I just see a complete black image

I checked your code, and it seems like the text-to-png cannot deal with new lines. The ascii_string has new lines for each of the rows. However, text-to-png transforms it into a huge one-liner. That's why #### works - it's short, but not ascii_string.

You can check this by changing:

    // this seems to work
    let ascii_img = ascii_string_to_img("######");

to something with new line in it, and see what image is generated.

    // this will generate a one line with the space instead of new line
    let ascii_img = ascii_string_to_img("####\n####")

Edit. More precisely, this line in text-to-png generates the final SVG with text from this template, you could probably fork the crate and change the code to use <tspan>s within. Something like this:

let example = "@@@@\n@@@@".to_string();
let mut tspans = String::new();
example.lines().for_each(| line | {
   tspans.push_str(&format!(
       "<tspan x=\"0\" dy=\"1em\">{}</tspan>", line)
    );
});
let content = format!(
    include_str!("../template.svg"),
    font_size, "#000000", tspans
);

Hope it helps!

thank you so much for the detailed response :slight_smile: however it seems too much (forking and editing part... T_T) , is there any other crate that could handle new line for me or is there any way to get away with it?

Unfortunately, I don't know any other crate to do this. But if you can tolerate extra few crates in your dependencies and extra two files (font and SVG template), you can replicate it yourself.

Font is needed, because the options parameter is, unfortunately, private. Both files can be found here.

I included the full example here, let me know if this help :slight_smile:

It uses resvg under the hood. SVG unfortunately doesn't have multiline text layout, and needs to be given lines of text split manually.

I'm using resvg directly:

https://gitlab.com/lib.rs/main/-/blob/main/svg_render/src/lib.rs?ref_type=heads

but I have to split text and do the layout the hard way:

https://gitlab.com/lib.rs/main/-/blob/main/front_end/templates/preview.rs.xml?ref_type=heads

Really thankful for the help but in the meantime I was looking out for ways on my own too and came across ab_glyph so decided to give it a try , had to learn bit more deeper but it finally worked, I ended up mapping the bitmap on the canvas ( each bitmap itself comprised of several pixel value, so draw under the hood , iterates onto each on it , so that was really helpful )

Here is the soln I was talking about Asciify/src/ascii/img.rs at main · devnchill/Asciify · GitHub

thought you might be interested too