%% Write Image Tile to YCbCr TIFF File
% Read two tiles from a YCbCr 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_YCbCr_tiled.tif','r');
[Yr,Cbr,Crr] = read(tr);
nTiles = numberOfTiles(tr)

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

[Y8,Cb8,Cr8] = readEncodedTile(tr,8);
[Y29,Cb29,Cr29] = 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.SampleFormat = getTag(tr,'SampleFormat');
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.YCbCrSubSampling = getTag(tr,'YCbCrSubSampling');
tagstruct.Compression = getTag(tr,'Compression');
tagstruct.PlanarConfiguration = getTag(tr,'PlanarConfiguration');  
setTag(tw,tagstruct); 
write(tw,Yr,Cbr,Crr)

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

writeEncodedTile(tw,8,Y29,Cb29,Cr29);
writeEncodedTile(tw,29,Y8,Cb8,Cr8);

% Read and display the Y component of the new image next to the original image.

[Yw,Crw,Cbw] = read(tw);
subplot(121);
imshow(Yr); 
title('Original Image (Y)')
subplot(122);
imshow(Yw); 
title('Tiles Shuffled Image (Y)')

% Close the Tiff objects.

close(tr);
close(tw);

% Copyright 2012 The MathWorks, Inc.