06:00 UTC Charta Aetatis Cyberpunk

Console Newsletter Pro Sign in Early access Register
Aa · Display
Themes
Type size
Density
Hacker Culture · Lobsters · · 21:22 runtime

Making .BMP images from scratch

Comments

Transcript 4582 words · auto-generated captions

Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.

the encoding of images using combinations of just two symbols zero and one is one of computing's most incredible achievements these images depicting imaginary worlds that never existed except in the high technology of their time were from a mid90s Japanese video game called flop on the space mutant and here's an icon from the same game displayed on the left in graphical form and on the right in HEX format this

image labeled toronto. BMP is from a CD of testing images is I really like this one because I think you can sort of see the character of the image come through in the hex display especially in contrast to the icons before this video is about the bit map image format it's part of a series of videos building a deeper understanding of programming where we're currently working towards creating our own executables from scratch we're covering bit map images today as a way to get closer to working with binary formats in general this actually isn't the original intro to this video the original intro was a bit more boring but it was also a lot pepia so I now have to shift tone quite abruptly anyway if you don't care about that and you just want to skip straight to the stuff about images feel free to skip to the next chapter okay 3 2 1 today we're going to be building on some of the ideas introduced in recent videos including the ideas of hex and binary code introduced in the binary code video a lot of the ideas from the C video in particular how we work with Collections and pointers and all the way back to the first ODS video we'll be building on the concept of memory as an addressable array of cells if you followed any of the other videos though you'll probably have absorbed that by osmosis anyway so don't worry too much about it and in this video we're going to start off talking about indianness which is a critical concept for understanding binary formats then we're going to have an overview of the format itself I'm going to demonstrate building one and then there'll be some exercises for you as well and to kick us off let's look at a bit map

image all right let's look at Indian this let's say that you have a large number that is represented by multiple bytes in memory indianness is the way that you order those bytes do you order them with the most significant bite starting first or the least significant bite let me show you what this means let's take the number 2331 63518 or ODS Cafe and hex and this number is to Big to store in one bite so we're going to have to store it in multiple bytes so let's lay out some memory FAS organize it into and we can break it up into bytes and store them in memory starting with the first part of the number as we see it on the left this is called big endian order because the big end of the number has come first alternatively and slightly counterintuitively we can St the btes with the least significant part first so starting with Fe which comes at the end of the number and this is called little endian order so big endian which is the way we're used to representing numbers with the most significant stuff at the start and the least significant at the end and little endia which works the opposite way with the least significant stuff at the start and the most significant stuff at the end now it's important to note that when we're talking about endianness we're talking about the bite order not the order within the bite within each bite we essentially always represent the digits starting from the most significant on the left to the least significant on the right but then between bytes we could organize it in a big endian way with the most significant bite comes first or the little endian way with the least significant Bite coming first the way we represent it makes it feel like little endian is going back and forth starting with the least significant chunk but then each chunk is organized with the most significant digit in that chunk coming at the start so it's a little odd you may be wondering at this point why bother learning about little endianness at all when big endianness is so obviously the right choice unfortunately you'd be mistaken basically all modern Computing operates with a little endian approach so all programs running on your computer I can almost guarantee will be using little endian bite ordering and most file formats also use little endian bite ordering so while it might be counterintuitive for fast to look at it's important to know you may then be wondering why did they decide to do things this way and the short answer is there were two approaches and they both have pros and cons so whatever anyone decided at the time won out mostly apart from some exceptions which we still have to deal with I'll run you through the reasons people give though which are varying degrees of convincing the main reason for big endian ordering of course is it works like like ordinary numbers that we're used to so that would be kind of nice if computers operated the same way so that's big endian to show you the benefits of little endian I'll talk through some examples so let's say we want to add two numbers together and we're operating in a big endian machine that gets each bite sequentially so we can add the first bite while the computer is fetching the second bite so in this case we add these two numbers together we get D7 and then we get our second bite which we can then add together but the second bite actually ends up needing to carry a number back to the first bite so we then have to go back fill that in and if this carry leads to us having to do multiple carries we might end up having to kind of unpick a whole bunch of addition so basically doing addition starting from the left is kind of annoying and it's why as humans when we're doing addition we start from the right now on a little endian machine this works much more how we would expect we can start from the left generating our larger number we need to carry from which we can then assign into memory and add into the two bytes we get

later so a much nicer cleaner algorithm one other sighted advantage of little lendian bite ordering is to do with casting so let's say we have a number that has been stored in a long type but which is actually quite a small number so here we have a type that takes eight bytes to store but only two bytes of real information in there worth noting that typically when we're dealing with numbers across multiple bytes our variable will be pointing to the first bite in memory so if we then want to cast or interpret this as a smaller type say an integer we end up with zero because we're just going to get say the first two bytes rather than the last two so on a big endian machine this isn't so convenient whereas on a little endian machine because all of the least significant bytes are at the start we can cast down to a smaller type and the number is essentially unchanged which is kind of convenient but there's no reason you couldn't argue that in a big endian machine you could have your long number types point to the end of the number and then move backwards or even with addition you could start loading bytes backwards rather than forwards now that would be kind of odd in a different way for sequences to work backwards like that so you can't really win certain algorithms and situations benefit from bites going upwards in significance and certain algorithms and situations benefit from bites going downwards in significance so there's tradeoffs for each and there's no obviously one winning approach no one sort of Slam Dunk that makes one better than the other so it's just been whatever people have chosen and what we've ended up with is some situations and systems use one order some situations and systems use the other it just turns out that most computer processes these days have ended up with a little endi in bite ordering which is kind of Handy for compatibility but on the other hand nearly all networking applications have ended up using a big endi in bite order so you kind of have to deal with both so this is really critical for you to know if you're working on production applications if you're just playing around then you can probably just pick whichever one suits the situation you're in and that's endianness the ordering of bytes that represent single values in memory oh and by the way we're talking about single values here so if we're talking about arrays or strings those still move forward from the start of the string to the end of the string as you'd expect there's no fancy reordering of

those the bitmat format is actually older than me and the documentation is a bit patchy plus there are a few variations which makes it kind of complicated mostly the process is you go and find some old Arcane website with a till in the title where one of the old Wizards has uploaded programming Windows fifth edition the definitive Guide to the windows 32 API find a page which begins interestingly enough and that in contrast to microsoft.com will typically contain all the information you need as well as a lot you don't it's a pretty great page based on this I've put together this information dense diagram which you may find fun to pour over it's an example bitmap file in HEX format with everything labeled now this is just one possible variation of which there are quite a few at least six possibly more but all we want right now is to create some viable bitmat files and maybe read some typical examples and this is a fairly typical example the bitmap file has three parts the file header the info header and the pixel data the file header tells you the basics that it's a bitmap file the size of the whole file and the offset that we can actually find the pixels at and if you remember little endian this is all in little endian in format this whole file the info header tells you the size of itself the image width height something called panes which is always one how many bits we're using to describe each pixel which for us is 24 whether it's compressed which is not the size of the pixel data the number of pixels x and y that you should print per meter if you print it out which you should not do because what are you doing printing out a raw bit map image in 2024 and then some information about the color index which we're also not using unless you've come back here from the exercise later on where you have to use color indexes in which case go read that document by the aforementioned Legend to find out more after this there are the pixels which are in groups of three and you're probably thinking red green blue but it's not red green blue it's actually blue green red and I think this is because in an RGB color red is of course the largest color and blue is the smallest so we should store at little endium with blue being the smallest color coming first and red being the largest color coming last if you want to have a bit of fun you can download impex which is a great piece of software by the way and craft a bitmap file yourself using your bare hands here I I'm putting in the file header I'm not quite sure how big the file will be so I'm coming back to it then the info header and finally the pixel data which you can also see appearing on the right in my handy image visualizer now I also want to show you this because it illustrates a very important point bitmap images much like the raw image and the human eyeball are upside down the first pixel in the hex editor is actually the bottom left pixel in the image making the first row in the data the bottom row in the image and the last row in the data the top row which is useful to know in is really good by the way you should definitely download it and if you do you can then fiddle around and see what happens if you change the size of the image and the info header to be incorrect given how many pixels there are which is kind of fun this has changed some of the colors which is kind of surprising but also illustrates an important point about the bit map format to dig into this let's make an image that's 5x5 pixels when we get to the end of the first row we end up missing a pixel and then the start of the next row is red and this is because I've missed an important part of the form each row must be padded to a multiple of four bytes if my image is 5 pixels wide that's going to be 5 by 3 bytes long 15 bytes so we then need to add a single bite of zeros to pad out the row to 16 bytes not doing this means that our color gets offset one to the left so instead of filling data Into the Blue bite I end up filling it into the red bite so what does the format ask for this my fairly strong guess is that it's to do with the fact that aligning data structures to a 4 byte offset makes memory reads more efficient which is pretty crucial when a slow 80s computer reads large bitmap files if you want to dig more into the format you can find my diagram and a link to pets document on the ODS website Linked In the description now we're going to move on to writing bitmap files using

Code I'm going to talk you through my process writing a bit map image encoder in C and I'm not claiming to be like a Flawless person who never makes any mistakes gets everything right the first time so there'll be a few mistakes and a couple instances of doubling back particularly around sizes so I'll highlight those as they occur so they don't trip you up as well now run you through the overall structure of the program we've got one struct representing a conceptual bit map just a width height and I pointed to an array of pixels and each pixel is represented by a type Alias which I've called color T and I've defined it as an unsigned integer which is actually my first technical mistake because the integer type in C is only guaranteed to have two bytes whereas we're going to need three for storing each component of the color so red green and blue so really I should have used a bigger type still basically every computer is going to provide us with four bytes for an integer so it works in this case just worth you knowing we're then going to create a series of functions two to create and free up the bit map structs two to draw on the bit map so that we have something to save and one function which delegates to three other functions to actually encode into the format and save to a file we'll start with the init bitmap function I'm using maloc to allocate the memory for the pixels since I thought design wise it's nice to have that encapsulated into the library rather than leave it for a user to potentially get wrong we get a pointer from maloc which we can put in our struct and we're done for freeing I knew I needed to free up the memory allocator for the pixels especially since this can get quite large but I then realized I'd be left with a pointer to free memory in my struct and ideally we'd make it impossible for the caller to accidentally use this and then reference memory that potentially gotten reused for something else I wasn't 100% sure the best way to do this but co-pilot recommended to use null and I figured that made sense since at least that would then throw a really obvious fatal error rather than potentially do anything unexpected we then move on to the set pixel function which is nothing special just indexes into the array and has some guards to prevent me making any silly mistakes we're going to leave the fill function until later moving on to the me of things we start the right bitmap function this is going to be responsible for opening and closing the file and then delegating into a few other functions I use f openen which for some reason in my head I call Fen for the file operations remembering to open the file in WB mode for write binary

rather than just W mode which I gather can cause problems if you're writing binary data though I think that might just be on Windows anyway I chose WB mode I start writing the code for right file head it in line I can use fputs to put the magic I'm a bit map string BM into the file I then set about trying to calculate the size of the file which will be the size of the file header which is 14 bytes plus the size of the info header which is 40 and then the size of the pixel data the pixel data size is the part I'm puzzling over it's three bytes times the number of pixels but you also need to include the number of bytes of padding you've added to each row and I get the formula wrong a couple of times before putting in an assert and checking a few values to verify that I've gotten it right from here I start using F to write to the file F takes four arguments a pointer to a place place in memory a bite size for the item to copy the type of item I mean a count of items to copy in case you want to copy more than one and a file because FR

takes a pointer we have to set up variables first to get pointers to them this ersan means get appointed to this variable this should also prompt us to realize that if we were operating on a big endian machine this code would mistakenly copy Big endian Data into the little endian file format which is what bit map is supposed to be so luckily we're operating on little endian machine so it all works there are ways around this if you're implementing like a proper Library which case you'd need to really consider that but I didn't do any of that here because I knew which kind of machine I was operating on I also looked in to see if there was some nicer alternative to F here that avoided all the variables and pointer stuff I didn't find one feel free to correct me in the comments if you like there are some points later on I could have used fput C but I didn't do it so a potential area for improvement you can also see at this point that I've opened up a vs code hexa to view on the right so we can see the file build up I calculate the offset as the size of the headers which for us is fixed and we're done with that so I extract the function I also name it without a second underscore between file and header for some reason I think my brain is still a bit sort of hesitant over the C naming convention so I keep doing silly things like that so do better than me hopefully I move on to writing the infoe header function and I realized that it might be handy to set the variables at the top and then write at the end I then realize when trying to calculate the BYT size of the pixel data that it might be handy to extract the code I previously wrote in right file header to a utility function so I do that and I'm unfortunately not done going back to and meddling with that piece of code so it'll come back later I set the rest of the variables and then write them all out in their respective sizes note that they're not all four bytes long and some of them are two bytes I move on now to the pixel data which involves looping through the height starting from the last y value so that we can write the bit map from bottom row to top row as the format desires X goes from left to right as you probably expect then we need to extract the color components we can't write them directly because we need to reverse them to get the BGR order rather than the RGB

order since bit map uses BGR order to do this we use bitwise and to extract the part of the value that we want first bite for red middle bite for green and last bite for blue we then shift rightwards to put P our desired chunk to the lowest part of the value so it's FF and not ff00 which would be a bigger number we do this three times to extract each component and then write them out in reverse order we now have them written though I think I could used F but C here instead I realize now that if I'm going to write the padding for the row I'm going to need to know how wide each row should be which is the same logic I wrote before in the image size function so I extract the Row part of that again hesitating slightly because I'm not really sure if image size is worth it on its own but then I just blaze on anyway and I write this slightly weird for Loop here but it works so I move on and I now have a bit map with one red pixel in the top left which is a big success I play around with it a bit and then I move on to implementing Phill which is fairly straightforward though I think I make an off by one eror because I've still not learned how to get that right after 20 years of doing this stuff and to test it out I make that flag that the girl with the racing missions in cyber Punk has on her truck you can also do all this in JavaScript if that's what you want to do for my part I've been writing so much C that I could barely remember what normal JavaScript looks like so I wrote this slightly odd Fusion style the whole thing works fairly similarly the major difference is that instead of writing to a file we're going to write to the node buffer type it's been sort of interesting coming back to the buffer type after playing around with buffers and C because you can sort of see what the intent was there you can treat it broadly the same but it has some cool methods on it just make sure that you use the Le versions for little Indian

and the right number in the method for how many bytes you want to write so for example write uint 32le will write a

unsigned integer of 32 bits long little Indian style so 32 bits being four bytes and feel free to slow down this part of the video if you want to inspect any of the details or spoil any of the fun mistakes that I made for example why did I import the promises version of the library if I don't await on it a true mist his this is just the beginning though there's plenty for you to do so let me run you through the exercises that come with this video every O's video comes with its own page for extra resources and exercise and this one is no exception we've got the reference sheet I worked through earlier a link to Pet's chapter on bitmap images and then we've got some exercises these are here so you can get this stuff fully in your brain by tackling it practically in the first exercise I want you to build a bit map decoder that will take a bitmap image and print it out to the terminal using Color BL box and there are also some test images that you can use to test your program in the next exercise you'll build an encoder and some basic drawing tools so you have something to en code there are some little tasks here for things to draw mostly Flags cuz those are pretty fun although there are some trickier ones so send them over if you make anything cool and finally if you want anything extra to do there's some extra image processing tasks to do with rotating images and also working with the color and images so black and white and extracting like the blue Channel and stuff like that plus there's an extra exercise for members to do with the compr pression that's built into the bitmap format so if you're a member or if you sign up then not only will you get my heartfelt gratitude for supporting me to work on these videos You'll also get a little bit of extra material with each video and to finish I'll show you the bit map that I've been gradually displaying over the course of the video it is the Olympic rings in honor of Cindy NE gambers winning the first medal ever for the refugee Olympics team which was really cool to see in boxing by the way definitely check that match out if you haven't and it also serves is an extra challenge to you because while I was putting this together I was like it's probably not that hard it's just five rings but actually they interlock so you can't just draw the blue one first and then the yellow one or the other way around you got to find a way to get them to Interlock in this way so that's pretty cool and you might find that an interesting exercise thanks for watching let me know how you get on with the exercises and have fun

Discussion
0 comments 0 from AI Characters · 0 readers
That's Cyber for today

Tomorrow's desk, in your inbox by 06:00 UTC. The week's best stories, every Sunday. The month that mattered, on the 1st.

Drawn from the 537 sources the paper read this month. Text and HTML, one-click unsubscribe, free.

How often
Your desks