Losslessly Joining JPEGs with JPEGTran

The Introduction

On occasion, you may find that you need to join – or tile – two or more JPEG images into a single image and that you need to do so without the usual JPEG degradation that comes from saving an edited JPEG again and again and again. Fortunately, under some circumstances, there is a solution – JPEGTran from the Independent JPEG Group.

The Images

Our sample images are two tiles taken from The Map Project – in this case map Yorkshire Sheet CLXXIV.SW, a 1950s map of south-west York in the United Kingdom.

‘Image_A.jpeg’ Details
‘Image_B.jpeg’ Details

In this example, we want our images to tile with the ‘Image_A.jpeg’ on the left and ‘Image_B.jpeg’ on the right, resulting in a composite image in the format ‘Image_A.jpeg | Image_B.jpeg’.

Our ultimate goal.

The Process

Joining our images is a two step process :

  • Expand a copy of the original image so that it is large enough to hold both the original image and the second image we wish to add
  • Place the second image into this new space.

Expand a copy of the original image

First we need to expand the canvas of ‘Image_A.jpeg’ so it is wide enough for our second image. Jpegtran can do this with a command in the following format.

jpegtran -crop <NewWidth>x<NewHeight>+0+0 -outfile <OutputFilePath> <SourceFilePath>

…here <NewWidth> and <NewHeight> are measured from the top left.

For our two images we would use the following values:

jpegtran -crop 1024x512+0+0 -outfile ./expanded_Image_A.jpeg ./Image_A.jpeg

Which would result in the following image.

Our ‘expanded_Image_A.jpeg’ file.

The expanded area, in grey, is easily visible.

Place the second image into this new space.

We then need to place the second image in the free space of our new image. The generic formula for this is:

jpegtran -drop +<x>+<y> <SecondImagePath> -outfile <OutputFilePath> <ExpandedImagePath> 

…where <x> and <y> are co-ordinates relative to the top left of our expanded image.

For our example images this would become…

jpegtran -drop +512+0 ./Image_B.jpeg -outfile ./complete_Image.jpeg ./expanded_Image_A.jpeg

Which would produced the following image.

Our ‘complete_Image.jpeg’ file.

And of course, this entire process can be repeated over and over again so that a large number of smaller images can be tiled together to produce a single, very large image.

Leave a Reply

Your email address will not be published. Required fields are marked *