全部,TIFF文件解析C#
我有一個標準的TIFF文件與我。我需要編寫C#代碼來讀取TIFF文件中每個像素的數據。例如,我不知道數據在這個文件中的起始位置等。有人可以指向我的一些鏈接,我可以在C#中獲得示例代碼。
感謝您的幫助!
全部,TIFF文件解析C#
我有一個標準的TIFF文件與我。我需要編寫C#代碼來讀取TIFF文件中每個像素的數據。例如,我不知道數據在這個文件中的起始位置等。有人可以指向我的一些鏈接,我可以在C#中獲得示例代碼。
感謝您的幫助!
我會建議使用TiffBitmapDecoder類。一旦創建了該類的實例,就可以訪問Frames集合。此集合中的每個幀表示TIFF文件中單個圖層的位圖數據。您可以在各個幀上使用CopyPixels方法來創建表示圖像像素數據的字節數組。
更新:
namespace TiffExample
{
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
public static class Program
{
private const int bytesPerPixel = 4; // This constant must correspond with the pixel format of the converted bitmap.
private static void Main()
{
var stream = File.Open("example.tif", FileMode.Open);
var tiffDecoder = new TiffBitmapDecoder(
stream,
BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreImageCache,
BitmapCacheOption.None);
stream.Dispose();
var firstFrame = tiffDecoder.Frames[0];
var convertedBitmap = new FormatConvertedBitmap(firstFrame, PixelFormats.Bgra32, null, 0);
var width = convertedBitmap.PixelWidth;
var height = convertedBitmap.PixelHeight;
var bytes = new byte[width * height * bytesPerPixel];
convertedBitmap.CopyPixels(bytes, width * bytesPerPixel, 0);
Console.WriteLine(GetPixel(bytes, 548, 314, width));
Console.ReadKey();
}
private static Color GetPixel(byte[] bgraBytes, int x, int y, int width)
{
var index = (y * (width * bytesPerPixel) + (x * bytesPerPixel));
return Color.FromArgb(
bgraBytes[index + 3],
bgraBytes[index + 2],
bgraBytes[index + 1],
bgraBytes[index]);
}
}
}
我在哪裏可以得到bytesPerPixel值在C# – 2015-03-13 02:10:23
@shijiexu我還沒有嘗試過這個我自己,但它看起來像你要找的是'BitsPerPixel'屬性,可以在'PixelFormat'結構中找到。在上面的例子中,你可以嘗試'firstFrame.Format.BitsPerPixel'。 https://msdn.microsoft.com/en-us/library/system.windows.media.pixelformat.bitsperpixel(v=vs.110).aspx – Dan 2015-03-13 22:34:50
您可以將文件加載爲位圖,然後使用位圖上的GetPixel或LockBits函數。 GetPixel很簡單但很慢。 LockBits稍微複雜一些,但速度非常快。
代碼會是這樣的
VAR位=新位圖(文件名) bitmap.GetPixel(0,0)
對於lockbits只是做一個網絡搜索有很多的文章。
鮑勃鮑威爾有一大堆的信息對這樣的:
還有一些TIFF庫,可以幫助:
Additionaly羅確定在MSDN指南:
https://www.google.com.au/search?q=C%23+TIFF+file。不意味着粗魯,但你使用了什麼搜索詞?我只是輸入「C#TIFF文件」,並且有很多鏈接。 – 2012-08-03 00:46:23
如果他使用了Google,但他可能會用一些非常複雜的代碼來手動解析文件。 – MikeKulls 2012-08-03 01:20:10