Android Question Convert PNG to 24Bit Colordepth

MarcRB

Active Member
Licensed User
Longtime User
Hello,

I need to convert a PNG to lower colordepth, in order to use it with cPDF.
Sure I know it can be down with Paint.NET, Irfanview and other graphical programs.
But in this case I have to convert it inside B4A project.
For example PNG 32 bit to PNG 24 bit.

I had no idea how to manipulate the colordepth. So I started a search on this forum.
At last I tried ChatGPT. Both didn't result in a complete solution.
Maybe someone can help to make it work.

Line 10 and 27 wil not work.
Maybe 27 can be solved by using canvas to draw each pixel als a line with same x1 & x2 and y1 & y2.
Maybe it can be solved by a complete different function.

ConvertTo24BitColorDepth:
Sub ConvertTo24BitColorDepth(inputFilePath As String, outputFilePath As String)
    Dim inputBitmap As Bitmap
    Dim outputBitmap As Bitmap
    
    ' Load the input PNG image into a Bitmap object
    inputBitmap.Initialize2(inputFilePath)
    
    ' Create a new Bitmap object with 24-bit color depth
    outputBitmap.InitializeMutable(inputBitmap.Width, inputBitmap.Height)
    outputBitmap.SetDensity(inputBitmap.Density)
    
    ' Copy the pixels from the input Bitmap to the output Bitmap, converting the color depth
    For x = 0 To inputBitmap.Width - 1
        For y = 0 To inputBitmap.Height - 1
            Dim pixelColor As Int
            pixelColor = inputBitmap.GetPixel(x, y)
            
            ' Convert the color depth from 32-bit to 24-bit by discarding the alpha channel
            Dim red As Int
            Dim green As Int
            Dim blue As Int
            red = Bit.ShiftRight(Bit.And(pixelColor, 0xFF0000), 16)
            green = Bit.ShiftRight(Bit.And(pixelColor, 0xFF00), 8)
            blue = Bit.And(pixelColor, 0xFF)
            pixelColor = Bit.Or(Bit.Or(Bit.ShiftLeft(red, 16), Bit.ShiftLeft(green, 8)), blue)
            
            outputBitmap.SetPixel(x, y, pixelColor)
        Next
    Next
    
    ' Save the output PNG image to a file
    Dim outputStream As OutputStream
    outputStream = File.OpenOutput(outputFilePath, False)
    outputBitmap.WriteToStream(outputStream, 100, "PNG")
    outputStream.Close
End Sub
 

agraham

Expert
Licensed User
Longtime User
It doesn't work like that. The final file format is determined by WriteToStream. As far as I can see in the Android API the only thing you can specify is to use the PNG format but not which format implying that only a single, presumably 32bit format is used when saving.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…