C#でlibtiffをつかう
2014年1月18日:libtiff
C#でlibtiffを使う方法を解説します。
導入
まず、Windowsフォームアプリケーションのプロジェクトを立ち上げます。
そして、プロジェクト名の部分で右クリックをし、NuGetパッケージの管理を選択します。
あとは、オンラインでlibtiffを検索して、「BitMiracle.LibTiff.NET」をインストールします。
これでlibtiffを使用できるようになりました。
コーディング
では、TIFFファイルを作成するプログラムを作ります。適当にボタンを配置し、以下のようにプログラムを組んでください。
private void button1_Click(object sender, EventArgs e) { int i, j, width, height; ushort samplesperpixel, bitspersample; double resolution; string fileName = "test.tif"; width = 256; //幅 height = 256; //高さ resolution = 72.0; bitspersample = 8; //8bit samplesperpixel = 1; Tiff output = Tiff.Open(fileName, "w"); if (output == null) return; output.SetField(TiffTag.IMAGEWIDTH, width); output.SetField(TiffTag.IMAGELENGTH, height); output.SetField(TiffTag.SAMPLESPERPIXEL, samplesperpixel); output.SetField(TiffTag.BITSPERSAMPLE, bitspersample); output.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT); output.SetField(TiffTag.XRESOLUTION, resolution); output.SetField(TiffTag.YRESOLUTION, resolution); output.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.INCH); output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK); output.SetField(TiffTag.COMPRESSION, Compression.NONE); output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); // 1行ずつ書き込む for (i = 0; i < height; i++) { byte[] line = new byte[width]; for (j = 0; j < width; j++) { line[j] = (byte)i; } byte[] buf = new byte[line.Length * sizeof(byte)]; Buffer.BlockCopy(line, 0, buf, 0, buf.Length); output.WriteScanline(buf, i); } output.WriteDirectory(); }
これで、ボタンを押すと、TIFFファイルが作成されます。
著者:安井 真人(やすい まさと)
@yasui_masatoさんをフォロー