%% Write Image Tile to TIFF File
% Read two tiles from a TIFF file and write them to a new TIFF file in different positions.
% Open a TIFF file with image data in tiled layout, get the image data and the number of tiles in the image.

tr = Tiff('peppers_RGB_tiled.tif','r');
imageR = read(tr);
nTiles = numberOfTiles(tr)

% Read the 8th and 29th tiles of the image.

tile8 = readEncodedTile(tr,8);
tile29 = readEncodedTile(tr,29);

% Create a Tiff object for a new file and copy the image and tag information from the first file.

tw = Tiff('write_tile.tif','w');
tagstruct.ImageLength = getTag(tr,'ImageLength');
tagstruct.ImageWidth =  getTag(tr,'ImageWidth');
tagstruct.Photometric = getTag(tr,'Photometric');
tagstruct.TileLength = getTag(tr,'TileLength');
tagstruct.TileWidth = getTag(tr,'TileWidth');
tagstruct.BitsPerSample = getTag(tr,'BitsPerSample');
tagstruct.SamplesPerPixel = getTag(tr,'SamplesPerPixel');
tagstruct.PlanarConfiguration = getTag(tr,'PlanarConfiguration');  
setTag(tw,tagstruct); 
write(tw,imageR)

% Write tile29 in the position for tile number 8 and tile8 in the position for tile number 29.

writeEncodedTile(tw,8,tile29);
writeEncodedTile(tw,29,tile8);

% Read and display the new image next to the original image.

imageW = read(tw);
subplot(121);
imshow(imageR); 
title('Original Image')
subplot(122);
imshow(imageW); 
title('Tiles Shuffled Image')

% Close the Tiff objects.

close(tr);
close(tw);

% Copyright 2012 The MathWorks, Inc.