On Tuesday, 26 April 2022 at 18:31:49 UTC, H. S. Teoh wrote:
maybe look at Adam Ruppe's arsd library (https://github.com/adamdruppe/arsd) for some lightweight modules that read common image formats and do some primitive image manipulations.

I don't actually have an image to image blit function, but writing one is trivial - just loop over it and call alphaBlend.

It can load ttf fonts, render them to bitmaps, load images, combined them, then save images. Can even load ttfs off the operating system if you wanted to use those.... or even have the OS functions do the drawing instead of diy, but probably easier to diy this simple case.

Sample code would be:

---
import arsd.image;
import arsd.ttf;

void main() {
        auto image = loadImageFromFile("/home/me/small-clouds.png");
        if(image is null)
                throw new Exception("Couldn't load the image file");
auto tci = image.getAsTrueColorImage(); // convert to rgba for simplicity

        import std.file;
auto font = TtfFont(cast(ubyte[]) std.file.read("/home/me/arsd/sans-serif.ttf"));

        int width, height;
auto bitmap = font.renderString("Hello", 14, width, height); // it populates width and height fyi

        // where we want to put it
        int xput = 30;
        int yput = 20;

        int bitmapOffset = 0;

        // color to draw the text
        int r = 255;
        int g = 0;
        int b = 0;

        foreach(y; 0 .. height) {
                if(y + yput >= image.height)
                        break;
                foreach(x; 0 .. width) {
scope(exit) bitmapOffset++; // always advance this as long as we're still drawing...
                        // but don't draw out of bounds
                        if(x + xput >= image.width)
                                continue;

                        // replace a pixel with the blended version of the text 
bitmap
                        image.setPixel(
                                xput + x, yput + y,
                                image.getPixel(xput + x, yput + y).
                                        alphaBlend(Color(r, g, b, 
bitmap[bitmapOffset]))
                        );
                }
        }

        import arsd.png;
        writePng("text-image.png", image); // save it back to a png
}
---


Open the text-image.png to see the result. (Or:
---
    import arsd.simpledisplay;
    displayImage(Image.fromMemoryImage(image));
---
to display it in a window right from your program!)



My libs are available as individual files from the github - you might just use png instead of the whole image.d to avoid needing additional files for formats you don't need - or you can pull it on dub under the arsd-official:image_files package and arsd-official:ttf.

Reply via email to