2014-07-16 38 views
0

在C#(.NET FW 4.5)中,有沒有一種方法可以理解字節串是否包含.svg文件或任何柵格文件?我使用這個程序:在ByteString中識別柵格(jpg,png等)或svg文件格式

[...] 
byte[] img = System.Convert.FromBase64String(res); 
ctrlImage = new BitmapImage(); 
ctrlImage.BeginInit(); 
MemoryStream ms = new MemoryStream(img);           
ctrlImage.StreamSource = ms; 
ctrlImage.EndInit(); 

到流轉換爲BitmpatImage,但現在我需要驗證,如果res包含SVG文件,而不是一個光柵文件。

謝謝。

回答

1

SVG文件格式基於XML。因此,你可以嘗試爲一個文本字符串從圖像緩衝區進行解碼,並檢查其是否與<?xml<svg開始:

bool isSvg = false; 

try 
{ 
    var text = Encoding.UTF8.GetString(img); 
    isSvg = text.StartsWith("<?xml ") || text.StartsWith("<svg "); 
} 
catch 
{ 
} 

或者,也許你只是檢查,如果在緩衝區中的第一個字節是<,因爲光柵圖像格式不從該字符開始:

bool isSvg = img[0] == '<'; 
+0

您的解決方案很有趣。但是,你確定光柵圖像格式不是以'<'開始的嗎? PS:「 rPulvi

+1

是的,我所知道的(並且受WPF支持的)都是從其他角色開始的。 – Clemens

+0

好的。無論如何,標識xml文檔的xml標籤應該是「<?xml」。你能將這個更正應用於你的答案,所以我可以將其標記爲正確的? – rPulvi

0

一旦成功創建解碼器,您就可以利用BitmapDecoder類並閱讀CodecInfo

樣品

FileStream stream = new FileStream(imagePath, FileMode.Open); 
    BitmapDecoder decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None); 
    // decoder.CodecInfo contains the information about the image type 
    stream.Close(); 

example

的情況下

byte[] img = System.Convert.FromBase64String(res); 
    MemoryStream ms = new MemoryStream(img); 
    BitmapDecoder decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.None); 
    // decoder.CodecInfo contains the information about the image type 
    stream.Close(); 
+0

我不知道BitmapDecoder ... CodecInfo真的很有趣。但是,如果我嘗試從非圖像源解碼,則會引發異常。也許Clemens的方法更好,因爲我可以避免可能會減慢應用程序流的異常。 – rPulvi

+0

這很明顯,如果你嘗試解碼會導致異常的非圖像源。答案是確定圖像的類型。 – pushpraj

相關問題