%% Write Image Strip to YCbCr TIFF File
% Read two strips from a YCbCr TIFF file and write them to a new TIFF file in different positions.
% Open a TIFF file containing YCbCr image data in stripped layout, get the image data and the number of strips in the image.

tr = Tiff('peppers_YCbCr_stripped.tif','r');
[Yr,Cbr,Crr] = read(tr);
nStrips = numberOfStrips(tr)

% Read the 2nd and 5th strips of the image.

[Y2,Cb2,Cr2] = readEncodedStrip(tr,2);
[Y5,Cb5,Cr5] = readEncodedStrip(tr,5);

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

tw = Tiff('write_strip.tif','w');
tagstruct.ImageLength = getTag(tr,'ImageLength');
tagstruct.ImageWidth =  getTag(tr,'ImageWidth');
tagstruct.SampleFormat = getTag(tr,'SampleFormat');
tagstruct.Photometric = getTag(tr,'Photometric');
tagstruct.RowsPerStrip = getTag(tr,'RowsPerStrip');
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 strip number 5 in the position for strip number 2 and strip number 2 in the position for strip number 5.

writeEncodedStrip(tw,2,Y5,Cb5,Cr5);
writeEncodedStrip(tw,5,Y2,Cb2,Cr2);

% 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('Strips Shuffled Image (Y)')

% Close the Tiff objects.

close(tr);
close(tw);

% Copyright 2012 The MathWorks, Inc.