I have a two-dimensional array of boolean values ​​(bool [] []), and I need to write this array to BMP. That is, for example, there is such a matrix:

[0 0 0 0 1] [0 0 1 1 1] [0 0 0 0 1] [0 0 0 0 1] [0 0 0 0 1] 

and I need to somehow get from it a .bmp file with the image of the number "1". That is, true - black pixel, false - white. How can this be done in D?

  • The bmp format is quite simple. If you generate a picture of the desired bit rate, then the title can be hard-coded. And then just copy the array with the bits there. The main thing to remember is that in bmp images are stored upside down. - KoVadim
  • And the width of the line should be aligned to the multiplicity of 4 pixels - zenden2k
  • What is the choice of bmp? - Dmi7ry pm
  • @ Dmi7ry, as far as I know, BMP as a format is quite simple and at the same time popular, which means there must be libraries for it in many languages, including D. - velikiyv4
  • For a hundred years, the de facto standard for raster graphics without loss of quality is png, there is no point in using bmp. - Dmi7ry 2:01 pm

2 answers 2

To write BMP, you can use, for example, the arsd library, from which you will need the bmp and color modules.

 import arsd.bmp, arsd.color; void main() { ubyte[][] image = [ [ 0, 0, 0, 0, 0, 0, 0, 1], [ 0, 0, 0, 0, 0, 0, 1, 1], [ 0, 0, 0, 0, 0, 1, 1, 1], [ 0, 0, 0, 0, 1, 1, 1, 1], [ 0, 0, 0, 1, 1, 1, 1, 1], [ 0, 0, 1, 1, 1, 1, 1, 1], [ 0, 1, 1, 1, 1, 1, 1, 1], [ 1, 1, 1, 1, 1, 1, 1, 1], [ 0, 1, 0, 1, 0, 1, 0, 1], ]; auto col = [Color.black, Color.green]; auto w = image[0][].length; auto h = image[].length; ubyte[] data; for (int j=0; j<h; j++) { for (int i=0; i<w; i++) { auto val = image[j][i]; data ~= col[val].r; data ~= col[val].g; data ~= col[val].b; data ~= col[val].a; } } auto img = new TrueColorImage(w, h, data); writeBmp(img, "result.bmp"); } 
     /* import imageformats.png; uint[][] im; foreach(i; 0..10) im ~= new uint[10]; im[4][5] = 0xff_ff_00_00; auto m = read_png("n.png").to_int; m[10][10] = 0xff_00_ff_00; write_png("1.png", m[0].length, m.length, m.to_byte); */ auto to_byte(uint[][] m){ ubyte[] data; union BI { struct{ ubyte b1, b2, b3, b4; } uint n; } int w = m.length; int h = m[0].length; foreach(y; 0..h){ foreach(x; 0..w){ BI bi; bi.n = m[x][y]; data ~= bi.b1; data ~= bi.b2; data ~= bi.b3; data ~= bi.b4; } } return data; } auto to_int(T)(T data){ uint[][] im; foreach(i; 0..data.w) im ~= new uint[data.h]; union BI { struct{ ubyte b1, b2, b3, b4; } uint n; } int n = 0; foreach(y; 0..data.h){ foreach(x; 0..data.w){ BI bi; bi.b1 = data.pixels[n++]; bi.b2 = data.pixels[n++]; bi.b3 = data.pixels[n++]; if(data.c == 3) bi.b4 = 0xff; if(data.c == 4) bi.b4 = data.pixels[n++]; im[x][y] = bi.n; } } return im; }