There are two types of images to consider:
vector images
and
raster images
. For raster images, you also need to choose the right compression format, for example:
GIF
,
PNG
,
JPG
.
Raster images
, like photographs and other images which are represented as a grid of individual dots or pixels. Raster images typically come from a camera or scanner, or can be created in the browser with the
canvas
element. As the image size gets larger, the file size grows as well. When scaled larger than their original size, raster images get blurry as the browser needs to guess how to fill in the missing pixels.
Vector images
, such as logos and line art are be defined by a set of curves, lines, shapes and fill colors. Vector images are created with programs like Adobe Illustrator or Inkscape and saved to a vector format like
SVG
. Because vector images are built on simple primitives, they can be scaled without any loss in quality without a change in file size.
When choosing the right format, it is important to consider both the origin of the image (raster or vector), and the content (colors, animation, text, etc). No one format will fit all image types and each has it’s own strengths and weaknesses.
Start with these guidelines when choosing the right format:
-
Use
JPG
for photographic images.
-
Use
SVG
for vector art and solid color graphics such as logos and line art. If vector art is unavailable, try WebP or PNG.
-
Use
PNG
rather than
GIF
as it allows for more colors and offers better compression ratios.
-
For longer animations, consider using
<video>
which provide better image quality and gives the user control over playback.
Reduce the file size
Image file size can be considerably reduced by ‘post-processing’ them after saving. There are a number of tools for image compression – lossy and lossless, online, GUI, command line. Where possible, it’s best to try automating image optimization so that it’s a first-class citizen in your workflow.
Several tools are available that perform further, lossless compression on
JPG
and
PNG
files, with no effect on image quality. For
JPG
, try
jpegtran
or
jpegoptim
(available on Linux only; run with the –strip-all option). For
PNG
, try
OptiPNG
or
PNGOUT
.
Use image sprites
CSS spriting is a technique whereby a number of images are combined in a single ‘sprite sheet’ image. Individual images can then be used by specifying the background image for an element (the sprite sheet) plus an offset to display the correct part.