Pregunta

My requirement is to convert a png file into 1 bit monochrome bitmap file. I have a UIImage object and I want to get the representation of it as a 1 bit monochrome bmp.

1) Is there any straightforward way to do this? I am ready to do this from scratch, but only if any readymade solution is not available. I glanced around Core graphics and Core image framework, but couldn't find anything relevant. Or is there any open source project available which implements this?

2) If I have to do this manually, I have some doubts about saving a bit representation for a pixel. I found bmp file format here.

  1. Create a bitmap header, following the file format. I am not sure whether all bmp versions (1 bit, 8bit etc) has same header format. Couldn't find any information on that.
  2. Iterate through all pixels of the png image, get the byte value of Red, Green, Blue (RGB). Do some calculation on these 3 values, to get a 1 bit representation. For example something like (pseudocode)

    for(each pixel){
        average  = (pixel.RValue + pixel.GValue + pixel.BValue)/3;
        if(average > 0x7f) //127
             bit  = 1;
        else
             bit  = 0;
        //bit has monochrome representation for this pixel, but how to store it?
    }
    
  3. Append these bits to bmp header which you already created.

I know how to iterate through every pixel in a png image, and so I can get the monochrome representation for that pixel. I also think I can do the header part, even though I haven't done it yet. But I have no idea how to deal with bits. Any help?

¿Fue útil?

Solución

Is there any straightforward way to do this? I am ready to do this from scratch, but only if any readymade solution is not available.

I can't tell you if there are readymade solutions to write BMP in iOS, but I can tell you that BMP is one of the few formats that is relatively easy to write from scratch.

Create a bitmap header, following the file format. I am not sure whether all bmp versions (1 bit, 8bit etc) has same header format. Couldn't find any information on that.

The Wikipedia article is quite informative. All BMP types have basically the same header format, the bitdepth is stored in offset 1Ch

Iterate through all pixels of the png image, get the byte value of Red, Green, Blue (RGB). Do some calculation on these 3 values, to get a 1 bit representation. For example ... Append these bits to bmp header which you already created.

Sounds right. Don't forget that rows can require some padding

But I have no idea how to deal with bits

Simply pack group of eight bits in one byte.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top