2012-03-20 51 views
2

我已經開始使用LibTiff.NET最近編寫tiff IPTC標籤,並發現了我在這裏的一些文件的奇怪行爲。我使用附帶LibTiff.NET二進制文件示例代碼,並將其與大多數圖像的工作正常,但有些文件是有這些行後的圖像數據損壞:LibTiff.NET追加模式錯誤?

class Program 
{ 
    private const TiffTag TIFFTAG_GDAL_METADATA = (TiffTag)42112; 

    private static Tiff.TiffExtendProc m_parentExtender; 

    public static void TagExtender(Tiff tif) 
    { 
     TiffFieldInfo[] tiffFieldInfo = 
     { 
      new TiffFieldInfo(TIFFTAG_GDAL_METADATA, -1, -1, TiffType.ASCII, 
           FieldBit.Custom, true, false, "GDALMetadata"), 
     }; 

     tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length); 

     if (m_parentExtender != null) 
      m_parentExtender(tif); 
    } 

    public static void Main(string[] args) 
    { 
     // Register the extender callback 
     // It's a good idea to keep track of the previous tag extender (if any) so that we can call it 
     // from our extender allowing a chain of customizations to take effect. 
     m_parentExtender = Tiff.SetTagExtender(TagExtender); 

     string destFile = @"d:\00000641(tiffed).tif"; 

     File.Copy(@"d:\00000641.tif", destFile); 

     //Console.WriteLine("Hello World!"); 

     // TODO: Implement Functionality Here 
     using (Tiff image = Tiff.Open(destFile, "a")) 
    { 
     // we should rewind to first directory (first image) because of append mode 
     image.SetDirectory(0); 

     // set the custom tag 
     string value = "<GDALMetadata>\n<Item name=\"IMG_GUID\">" + 
      "817C0168-0688-45CD-B799-CF8C4DE9AB2B</Item>\n<Item" + 
      " name=\"LAYER_TYPE\" sample=\"0\">athematic</Item>\n</GDALMetadata>"; 
     image.SetField(TIFFTAG_GDAL_METADATA, value); 

     // rewrites directory saving new tag 
     image.CheckpointDirectory(); 
    } 

    // restore previous tag extender 
    Tiff.SetTagExtender(m_parentExtender); 
     Console.Write("Press any key to continue . . . "); 
     Console.ReadKey(true); 
    } 
} 

開放後,我看到大多是空白圖像或多條黑白線代替已寫入的文本(我不需要讀取\寫入標籤來產生此行爲)。我注意到這種情況發生時,圖像已經有一個自定義標籤(控制檯窗口警報關於它)或其中一個標籤有'壞值'(在這種情況下,控制檯窗口說'vsetfield:%pathToTiffFile%:壞%0爲%TagName% 「 標籤')。

原圖:LibTiff.NET後http://dl.dropbox.com/u/1476402/00000641.tif

圖片:http://dl.dropbox.com/u/1476402/00000641%28tiffed%29.tif

我會爲提供任何幫助表示感謝。

回答

4

對於在追加模式下打開的文件,您可能不應該使用CheckpointDirectory方法。請嘗試使用RewriteDirectory方法。

這將改寫該目錄,但不是將其放置在它的老 位置(如WriteDirectory()將),將它們放置在 結束的文件,從前述的目錄或文件修正指針 標題指向它的新位置。 當目錄的大小和指向數據的大小爲 增長爲時,這是特別重要的 ,因此它不適合舊位置可用的空間。 請注意,這會導致以前使用的 目錄空間丟失。

+0

感謝您的提示,我會盡量在一兩天內完成。 – cookieMonster 2012-03-23 06:01:11

+1

它完美的作品,謝謝! – cookieMonster 2012-03-26 13:16:47