You can't just assume that if the image palette only has 2 colours that it's B&W - it might be red & blue for example.
To determine B&W, ensure every pixel = RGB(0,0,0) or RGB(255,255,255)
To determine grayscale, ensure every pixel = ((R = G) & (G = B)) ....
that is, R=G=B
Here's a routine i wrote a few years ago which determines the percentage of grayscale pixels (100% = confirmed grayscale). It can easily be tweaked to detect B&W instead, but I haven't included that. It's pretty fast, working directly with memory pointers in the image data.
Code: Select all
Structure RGBA
r.a
g.a
b.a
a.a
EndStructure
Procedure.f DetermineFileGrayscalePct(sPNGfile.s)
Protected *inrgba.RGBA, *red.Ascii, *green.Ascii, *blue.Ascii, *alpha.Ascii, x,y
Protected hImg, depth, ipixfmt, irowlen, steprow, width, height, bytesperpixel, pixels
hImg = LoadImage(#PB_Any, sPNGfile)
If hImg = 0
MessageRequester("Error", "Couldnt load " + sPNGfile): End
EndIf
width = ImageWidth(hImg)
height = ImageHeight(hImg)
If width < 1 Or height < 1
MessageRequester("Error", "Invalid dimensions " + Str(width) + " x " + Str(height)): End
EndIf
pixels = width * height
depth = ImageDepth(hImg)
bytesperpixel = depth >> 3
If StartDrawing(ImageOutput(hImg))
*inrgba = DrawingBuffer()
irowlen = DrawingBufferPitch()
ipixfmt = DrawingBufferPixelFormat()
If ipixfmt & #PB_PixelFormat_ReversedY ;start from the bottom and work upwards
steprow = (0-irowlen-irowlen) + (irowlen - (width * bytesperpixel))
*inrgba + (irowlen * height) - irowlen
Else ;start from the top and work down
steprow = (irowlen - (width * bytesperpixel))
EndIf
For y = 1 To height
For x = 1 To width
If (*inrgba\r = *inrgba\g) And (*inrgba\g = *inrgba\b) ;if R=G and G=B, it's a grayscale pixel
GrayCnt+1
Else
NonGray+1
EndIf
*inrgba + bytesperpixel
Next x
*inrgba + steprow
Next y
StopDrawing()
EndIf
FreeImage(hImg)
MessageRequester("Pixels", "Pixels=" + Str(width*height) + " GrayCnt=" + Str(GrayCnt) + " Non=" + Str(Nongray))
ProcedureReturn (NonGray/GrayCnt) * 100
EndProcedure
UsePNGImageDecoder()
sFile.s = "H:\halfgray.png"
Pct.f = DetermineFileGrayscalePct(sFile)
MessageRequester("Grayscale Detect", "This image is " + StrF(Pct,3)+"% grayscale")