# Understanding image types and optimizing them

Handling images when you are a web developer is not an easy task. Speed of connection to the internet is constantly improving yet it is still important to deliver optimized images. Because some users may still experience getting a decent connection speed or sometimes smartphones can only access degraded connection.

# The big picture

Among all the different types of images available for the webdev, there are mostly 2 main families: bitmap and vector.

## Bitmap images

The bitmap images is the most common image type: just a sequence of dots (or pixels) recorded independently.

Each pixel holds enough data for the software that displays it (image viewer, browser..) to recompose the final color properly.

The data each pixel holds depend of the color model. For displaying on a computer screen (or a phone screen), the color model often used is RGB which stands for RED — GREEN — BLUE (basically primitive colors).

A lot of different color models exist and have their own use. For example the model CMYK which stands for CYAN — MAGENTA — YELLOW — BLACK is the preferred model for printing on paper. Why ? Just because press printers have a slot for black ink which allows to have deep blacks printed on paper.

“ Ok ! So now we know bitmap images are made of pixels in RGB color model. But what does it mean practically ? And how does it translate into my computer memory ? “

Well, if you have some knowledge of computers, you probably know that the storage capacity of a computer is counted in Bytes. And 1 Byte is a sequence of 8 bits.

Each bit value can be 1/0 or True/False.. It is basically binary.. Then One Byte can take any value between 0 (8 bits with a value of 0) to 255 (8 bits with a value of 1).

Basically to know the possible values of single Byte, just multiply each bit possible result by every other bit possible value : 2*2*2*2*2*2*2*2 = 256

— The depth of an image —

“ Ok ! So a single pixel is made of Bytes ! And Bytes have 256 different values. But how does this translates into different shades of colors ? “

Well this is easy : one pixel assigns a single Byte to each channel of the color mode it belongs to.

We said earlier images used on screens were using RGB color mode, then a single byte is assigned to each composite color of the color mode:

Then now you understand something :

• there can be 256 shades of red
• and 256 shades of blue

Which gives 256*256*256 = 16777216 different colors !!

Yes, with only 256 shades of each primitive colors, we can make more than 16.5 million colors. Then the depth of the image is “3 bytes of 8 bits” or “24 bits”.

— RGBA or 32 bits —

“ Right this is very interesting but sometimes I see a different color mode: RGBA ! And sometimes I see images with a depth of 32 bits ? ”

RGBA color mode is just about stretching the above concept. It adds a fourth byte that stands for “ALPHA” or “Alpha channel” which basically is the transparency of the pixel.

“ Why do you talk about transparency ? Why do I need it ? “

Well, transparency is something that has appeared with Image Editing decades ago and is very important today.

Let’s say you are building a banking website with a certain CSS background color. Go for grey! And now you want to add a nice image of a credit card as an illustration. But your credit card has been photographed laying on a white table … It won’t really fit in..

Now open your image editor and remove the background :

By removing the background, you have just pushed the value of the ALPHA byte to 255 to the pixels you have “erased”. And the edges of the credit card probably have a transparency between 0 and 255 so it blends smoothly with the grey background of your website.

You can now change your website CSS background color at will. Switch from grey, to white, to yellow: the cutout image will alway look good. With the surrounding of the credit card being filled up by your website CSS background color value.

Basically your browser will compute what it displays by calculating the different layers of images overlapping each other and accounting for their Alpha channels.

Now You have learnt about Bitmap images. We will cover compression later .. It’s time for vector images now !!

## Vector images

Vector images is a completely different beast. Here we have no dot or pixel. The vector image is a sequence of instructions that is repeated by the software that displays the image.

The instructions of a vector image could translate in human language to something like :

“ draw a line with black ink starting on top of page and going south for 15 millimeters. Then draw a circle with a red ink with a diameter of 30 millimeters and a fill color as pink…. etc …”

As you can imagine a vector image doesn’t look at all like a bitmap image. It rather looks like a cartoon, a sign, a drawing, a sketch …

Here is an example of a vector image (yet converted to a bitmap image as Medium website doesn’t accept vector images to be used in Medium articles) :

I have added a pink background to this lovely plane so you can see it better.

and here is the full code for this plane:

`<?xml version=”1.0" encoding=”UTF-8" standalone=”no”?><! — Created with Inkscape (http://www.inkscape.org/) →<svg xmlns:dc=”http://purl.org/dc/elements/1.1/" xmlns:cc=”http://creativecommons.org/ns#" xmlns:rdf=”http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg=”http://www.w3.org/2000/svg" xmlns=”http://www.w3.org/2000/svg" xmlns:sodipodi=”http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape=”http://www.inkscape.org/namespaces/inkscape" width=”33.660679mm” height=”20.716875mm” viewBox=”0 0 33.660679 20.716875" version=”1.1" id=”svg1227" inkscape:version=”0.92.3 (2405546, 2018–03–11)” sodipodi:docname=”avion1.svg”> <defs id=”defs1221" /> <sodipodi:namedview id=”base” pagecolor=”#ffffff” bordercolor=”#666666" borderopacity=”1.0" inkscape:pageopacity=”0.0" inkscape:pageshadow=”2" inkscape:zoom=”0.35" inkscape:cx=”-539.24641" inkscape:cy=”67.721442" inkscape:document-units=”mm” inkscape:current-layer=”layer1" showgrid=”false” fit-margin-top=”0" fit-margin-left=”0" fit-margin-right=”0" fit-margin-bottom=”0" inkscape:window-width=”1920" inkscape:window-height=”944" inkscape:window-x=”1920" inkscape:window-y=”27" inkscape:window-maximized=”1" /> <metadata id=”metadata1224"> <rdf:RDF> <cc:Work rdf:about=””> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource=”http://purl.org/dc/dcmitype/StillImage” /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label=”Layer 1" inkscape:groupmode="layer" id=”layer1" transform=”translate(-107.9018,-146.03442)”> <g id=”g1206" transform=”matrix(0.35277777,0,0,-0.35277777,84.412131,243.85155)”> <path d=”m 88.7091,262.6309 -22.1242,14.646 95.4161,-0.266 z” style=”fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.1" id=”path50" inkscape:connector-curvature=”0" /> <path d=”m 88.7091,262.6309 -8.2969,-20.031 15.1684,9.977 66.4204,24.434 -73.2919,-14.38" style=”fill:#f6f2d8;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.1" id=”path52" inkscape:connector-curvature=”0" /> <path d=”m 80.4122,242.5999 19.2426,1.503 -4.0742,8.474 z” style=”fill:#dcd9c0;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.1" id=”path54" inkscape:connector-curvature=”0" /> <path d=”m 95.5806,252.5769 10.6613,-34.025 55.7591,58.459 z” style=”fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.1" id=”path56" inkscape:connector-curvature=”0" /> </g> </g></svg>`

As you can see it is real instructions !! On the opposite, if you try to read a bitmap image into a text reader, you will only get funny characters or gibberish as it is not intended to be read by a human.

A vector image is perfectly readable and understandable. Vector images are really just instructions !

Actually it is going a step further : this “plane” vector image is of SVG format and you can see that it really looks like HTML : it embeds tags like <svg></svg><path/> etc ..
Then, instead of adding your vector image as an image file such as plane.svg in-between HTML “image” tags, you can just pick some elements and add them in your HTML straight away!!

Pretty insane !!! :)
You can even add some CSS to them: animation, transparency, rotation …

# A quick comparison

In the real world, vector images will rather be used as small illustrations and Bitmap images for real life pictures (like taken with a proper camera or your smartphone camera).

Regarding the limitations and advantages :

## vector images

• vector images can be pretty small if the illustration is simple.
• they can be scaled at will without losing any quality : there is no pixel
• they are highly integratable into HTML

## Bitmap images

• they are used for real life pictures
• they can be sometimes very big, it is important to compress them
• they are complementary to vector images: just different uses …

Ok the tricky part now : you know the two different possible types of images but we also want to make your website faster. Then we need to optimize and discriminate.

# Vector file types optimization

— file types —

Vector images can come in various flavors. We have learnt they are just instructions but the software that you use may “package” these instructions into different formats.

The open source extensions for vector images are : .svg .eps .ps or even .html.

And a beautiful open source software to create vector images is for example Inkscape. Don’t hesitate to check it.

At the moment 99.8% of browsers can read .svg files ( https://caniuse.com/?search=svg )

Copyrighted file formats can be : .ai (Adobe illustrator), .cdr (Coreldraw) , and probably many others ..

These formats cannot be read by browsers as far as I know. So if you are using Adobe Illustrator to make images for the web, just export to an open source format such as SVG. (widely supported by browsers)

— optimization —

Vector files usually don’t need optimization. They are fairly small. But it is still possible to remove all the overhead. One good tool to do such is SVGOMG. SVGOMG will trim everything that is not an image instruction to make your file as light as possible.

Also there is the case you have a very complex drawing : lots of elements, lots of colors, lots of pen drawings … Then it is a good thing to compare the size of the vector file to its Bitmap equivalent.

Though because vector files can be scaled at will without changing their weight, it also depends of the dimensions of the final image you need. If you have a 100KB vector file. Converting it into a 150px * 150px bitmap image will probably produce a much smaller file. But if you need a bitmap of 1500px * 1500px then your bitmap will be much heavier …

Then always try to convert any complex SVG (bigger than 70KB) to its Bitmap equivalent.

# Bitmap file types and optimiziation

Ok now take a deep breath: this is the tricky part of Bitmap file formats and optimization :D

I have explained you that a bitmap image is made of pixels. Those pixels are a blend of primitive colors: 3 RGB Bytes or 4 RGBA bytes.

But all Bitmap file formats don’t work like that. Also imagine a bitmap image of 200px * 200px in size with a thin red border of 1 pixels all around it.

Basically, the top red border will be the same 200 pixels : { Red: 255, Blue: 0 , green: 0} or { Red: 255, Blue: 0 , Green: 0, Alpha: 0}.

“ 200 hundred times the same data written next to each other ? is it efficient ?”

Not really. It would indeed be better to write in our image : “repeat 200 times the pixel with those colors : { Red: 255, Blue: 0 , Green: 0, Alpha: 0}” and we would save a lot of memory space!!

This is compression ! (though compression algorithms are much more advanced than this)

So basically all Bitmap files on the internet nowadays are compressed. The original format .bmp is not really used anymore.
Some algorithm can even compress more than what we expect .. but then the image quality become degraded (we call it a lossy compression).

So let’s browse all file formats :

Disclaimer : I try to give general information as close to possible to what they really are. But some file formats are very deep and highly twistable. Please bear with me in case some information is not accurate. Also the big lines should be right.

## — BMP

As far as I know this one has little or no compression. Images are very heavy. https://en.wikipedia.org/wiki/BMP_file_format
Yet the wiki says some compression can be added and also it can have an alpha channel. (see wiki link to examine all the different available image depths and options)

## — JPG or JPEG

Probably the most popular bitmap image format for the past couple of decades. The compression algorithm is destructive: it will degrade the image quality (you won’t be able to recover initial image quality by no mean) and add artifacts.

Artifacts are tiny glitches in the image, especially in contrasty areas : around object edges..

The compression algorithm is quite complex and work with chunks (tiles) of the original images.

=> This is a very good format for the web. Noteworthy you can select the quality value (or compression amount ) you desire and find the proper balance between image weight and image quality. But be carefull: a JPEG image with a quality of 90% may give different sizes depending on the software you use. The quality value is relative, not only to the JPEG algorithm, but also to the software that will compress.

## — PNG

PNG is non destructive. It’s compression algorithm is very good and decrease a BMP image by a lot without actually changing the image at all.

PNG is great for working copies : an image you will save on your computer to work on and alter later.

But for the web the weight of an PNG image may still be too high for a speedy delivery of your HTML pages.

## — TIFF

The preferred format for photographers. It is lossless of course. And very advanced.
I told you earlier that a Byte is made of 8 bits. And our RGB image has one Byte per color channel.
TIFF format can accept channels made of 16 bits !!!! https://photo.stackexchange.com/questions/13893/is-tiff-really-of-higher-quality-than-png-24
Which means we not only get 16 millions colors per pixel but billions of colors !! (Also your eye can’t probably see them, and modern monitors can’t even show them except very expansive ones)

It is loved by photographers because cameras now have sensors so sensitive they can have 14 bits per channels. Also when you do HDR or image enfusing you may need 16 bits channels to edit an image. Even if your output image will be 8 bits per channel ..

So it is like a “Deluxe working copy” of an image. (TIFF images can be Gigabytes big ! whereas we web developers, try to make our images as small as possible and our images are most often below 100KB)

## — GIF

Gif is a different beast as each pixel is not assigned 3 or 4 different channels. Instead it works with a palette.

When you try to compress an image into GIF, the compression software will create a palette of 256 of the most used colors in the image.

And each pixel, instead of having a shade of blue, a shade of green and a shade of red, will be assigned a single color from the palette.

This allows GIF to be a rather well compressed format ( only one Byte is necessary for each pixel )

Also there is the possibility to have a transparency value. Yet this is not an alpha channel (with 256 gradients of transparency) but rather a boolean value: transparent — or not transparent.

It is a good format for images with splats of colors.

## — PNG 8bit

PNG is a bit like GIF. It works with a palette of 256 colors but can have a real alpha channel. Also the compression algorithm is much better than GIF. Prefer PNG 8 bit to GIF.

=> It is excellent for logos and simple drawings. It can produce extremely light files while preserving quality.

(Be careful PNG 8 bit is destructive as it shrinks the number of colors to 256 when PNG 32 bits is a lossless format)

## — WEBP

WEBP is a fairly recent format with incredible compression ratios. Some say it is 25% lighter than any JPEG for similarly looking compressed images.

It is indeed very good. And has less artifacts than JPEG. But it drastically smoothens out details .. So you better prefer JPEG for some images and use WEBP in some other cases.

WEBP is fairly well supported by browsers.
Approximately 95% of browsers can display them : https://caniuse.com/?search=webp

=> a contender to JPEG replacement

## — Other formats

There are a wealth of newer file formats in the pipes: HEIF, AVIF, JPEGXL with their qualities and drawbacks.. I will not dive too much into them at the moment as they are not fully supported by browsers at the moment (If at all).

So I keep this section open for more additions and reviews of these new formats.

## now WEBP vs JPEG, who wins ?

As Isaid WEBP is being considered the clear winner “on the paper”. It makes files smaller than JPEG.

Though compression algorithm doesn’t give similar results :

• webp : smoothen out detail
• jpeg : adds some artifacts

In order to help you decide, here is a quick comparison between an original image in the PNG format (that Medium may compress into Jpeg 90%) with a weight of 325KB, a Jpeg with a quality of 50% and a weight of 21 KB, and finally a Webp with a quality of 70% and a similar weight of 21 KB.

All images are originally 400px * 400px and stitched together into a single image.

( I have not taken the same quality for both JPEG and WEBP as I think taking pictures with a similar weight is the fairest )

edit: click on the above image to enlarge it before checking fine details between images. But basically Medium compression kinda kills the ability to compare.

First thing we see is that all images are rather acceptable, but The two images on the right are 15 times lighter in weight than the original.

here is a crop of the JPEG and WEBP 32 px * 32px around the flowers :

As you can see it is clear that JPG adds a lot of artifacts (but still try to preserve original details as much as possible) and WEBP smoothens out details without adding artifacts.
If you have a look at the flower branch on the right, the WEBP version is much cleaner but shows only shades of RED / BROWN as the JPEG image still shows some GREENISH colors.

For this very image WEBP looks cleaner. But sometimes you might try JPEG or PNG 8bit, and play with compression quality to get what you desire.

# Q & A

“ thank you for telling me all that. But well, how do I compress in the end ? “

Well it depends what you have :

• “I have a JPEG”

A JPEG is technically already compressed with a quality ratio from 0% to 100% (100% being close to the original but it is still a bt lossy). You can try decreasing the quality ratio even-though it is always better to compress to JPEG from a lossless format.

• “I have a PNG”

PNG is lossless. A working copy. You can compress to JPEG, WEBP or maybe PNG 8bits.

There are very good tools to compress:

Squoosh App is very good and can compress to the newest formats if needed. Though it is front ended: your own computer is compressing the image. Don’t try to use Squoosh App from a Raspberry Pi or even a low tier smartphone. You will get funny results.
Squoosh app is made by Google Labs and source code is public.

There are also tons of other compressors for you to browse...

One I like (because I made it) is picfairy.com : it will compress your image into various different images quality increments for JPEG and WEBP and also try to compress to PNG 8bits. So you can compare visual quality with final image weight. It can also convert SVG to Bitmap.

• “ my image is JPEG 70% quality but is still too big”

Just make sure you use an image with the right dimensions: if your image is 1000px * 1000px but you add the CSS rule `width: 200px;` to your image tag then you can probably squeeze your image a bit.

No need for too big images. Even if users have Retina displays, you can safely resize your image to 400px * 400px and use the above mentioned CSS rule.

In a perfect world, you would provide your users different images sizes depending on the fluidity of your HTML page. (thank you Bootstrap and Tailwind haha)

I will improve it over time.

Best

--

--

## More from Maxence Malbois

Rails coder and other things

Love podcasts or audiobooks? Learn on the go with our new app.