Convert bmp to jpeg using javascript

Viewed 1398

I already manage to manually create the bitmap of an uploaded image, by manipulating the color channels to obtain an 8 bit image. Now, i'm in the need of converting the bitmap to jpeg but i need to maintain the bit depth (8 bits depth single-channel) I can't use Canvas since when the conversion is done the resulting file is 24 bit depth. Anyone knows if this possible to use JavaScript to do this conversion, so i can have all the image manipulation on the client-side?

1 Answers

I think you got confused between color depth and pixel format, and I'll admit it's confusing, because this Nbits nomenclature is used everywhere while having completely different meanings.

E.g what we call PNG-24 is actually 8 bits * 3 channels (RGB) and PNG-32 is 8 bits * 4 (RGBA).

But to put it simply, JPEG format doesn't support indexed colors, it is always (at least)* TrueColor: 3 channels * 8bits => ~16.77 millions colors.
*since v9 it actually supports up to 12 bits per channel

What you want to do (single 8bits channel => 256 colors) is not possible, because the JPEG format itself doesn't support it.

Note that because of how JPEG works (merging visually similar colors) that wouldn't make any sense anyway to save a 256 colors image in JPEG. The JPEG algorithm will create back new colors that weren't in your original 256 bitmap, and you might very well end up with a bigger file than its bitmap equivalent.

So if you really want an 8 bit image with a single channel (256 colors), then look at formats that do support Indexed colors.
PNG is one of them, but indeed canvas won't help you there since the Canvas API only supports PNG-32 (8 bits per channel RGBA).
GIF is an other one, but I think only Safari does support exporting to GIF from a canvas element...

Related