文字コードを判別するバイト型配列を文字列に変換する方法は「バイト型配列のデータを文字コードを指定して文字列に変換する」で紹介しましたが、データの文字コードが分からなければ変換できません。ここでは、バイト型配列のデータから文字コードを判別する方法を紹介します。 .NET Frameworkでは文字コードを判別する方法が用意されていませんので、外部DLL、OCX等を使うか、自分でコードを書くかということになります。 Jcode.pmを参考にした方法次に示すコードは、私がJcode.pmのgetcodeメソッドを参考にして書かせていただいた(移植したつもり)メソッドです。バイナリ配列で渡されたデータが、JIS、Shift-JIS、EUC、UTF-8(もしくはASCII)のいずれであるかを判別し、結果をEncodingオブジェクトで返します。 ''' <summary> ''' 文字コードを判別する ''' </summary> ''' <remarks> ''' Jcode.pmのgetcodeメソッドを移植したものです。 ''' Jcode.pm(http://openlab.ring.gr.jp/Jcode/index-j.html) ''' Jcode.pmのCopyright: Copyright 1999-2005 Dan Kogai ''' </remarks> ''' <param name="bytes">文字コードを調べるデータ</param> ''' <returns>適当と思われるEncodingオブジェクト。 ''' 判断できなかった時はnull。</returns> Public Shared Function GetCode(ByVal bytes As Byte()) As System.Text.Encoding Const bEscape As Byte = &H1B Const bAt As Byte = &H40 Const bDollar As Byte = &H24 Const bAnd As Byte = &H26 Const bOpen As Byte = &H28 ''(' Const bB As Byte = &H42 Const bD As Byte = &H44 Const bJ As Byte = &H4A Const bI As Byte = &H49 Dim len As Integer = bytes.Length Dim b1 As Byte, b2 As Byte, b3 As Byte, b4 As Byte 'Encode::is_utf8 は無視 Dim isBinary As Boolean = False Dim i As Integer For i = 0 To len - 1 b1 = bytes(i) If b1 <= &H6 OrElse b1 = &H7F OrElse b1 = &HFF Then ''binary' isBinary = True If b1 = &H0 AndAlso i < len - 1 AndAlso bytes(i + 1) <= &H7F Then 'smells like raw unicode Return System.Text.Encoding.Unicode End If End If Next If isBinary Then Return Nothing End If 'not Japanese Dim notJapanese As Boolean = True For i = 0 To len - 1 b1 = bytes(i) If b1 = bEscape OrElse &H80 <= b1 Then notJapanese = False Exit For End If Next If notJapanese Then Return System.Text.Encoding.ASCII End If For i = 0 To len - 3 b1 = bytes(i) b2 = bytes(i + 1) b3 = bytes(i + 2) If b1 = bEscape Then If b2 = bDollar AndAlso b3 = bAt Then 'JIS_0208 1978 'JIS Return System.Text.Encoding.GetEncoding(50220) ElseIf b2 = bDollar AndAlso b3 = bB Then 'JIS_0208 1983 'JIS Return System.Text.Encoding.GetEncoding(50220) ElseIf b2 = bOpen AndAlso (b3 = bB OrElse b3 = bJ) Then 'JIS_ASC 'JIS Return System.Text.Encoding.GetEncoding(50220) ElseIf b2 = bOpen AndAlso b3 = bI Then 'JIS_KANA 'JIS Return System.Text.Encoding.GetEncoding(50220) End If If i < len - 3 Then b4 = bytes(i + 3) If b2 = bDollar AndAlso b3 = bOpen AndAlso b4 = bD Then 'JIS_0212 'JIS Return System.Text.Encoding.GetEncoding(50220) End If If i < len - 5 AndAlso _ b2 = bAnd AndAlso b3 = bAt AndAlso b4 = bEscape AndAlso _ bytes(i + 4) = bDollar AndAlso bytes(i + 5) = bB Then 'JIS_0208 1990 'JIS Return System.Text.Encoding.GetEncoding(50220) End If End If End If Next 'should be euc|sjis|utf8 'use of (?:) by Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp> Dim sjis As Integer = 0 Dim euc As Integer = 0 Dim utf8 As Integer = 0 For i = 0 To len - 2 b1 = bytes(i) b2 = bytes(i + 1) If ((&H81 <= b1 AndAlso b1 <= &H9F) OrElse _ (&HE0 <= b1 AndAlso b1 <= &HFC)) AndAlso _ ((&H40 <= b2 AndAlso b2 <= &H7E) OrElse _ (&H80 <= b2 AndAlso b2 <= &HFC)) Then 'SJIS_C sjis += 2 i += 1 End If Next For i = 0 To len - 2 b1 = bytes(i) b2 = bytes(i + 1) If ((&HA1 <= b1 AndAlso b1 <= &HFE) AndAlso _ (&HA1 <= b2 AndAlso b2 <= &HFE)) OrElse _ (b1 = &H8E AndAlso (&HA1 <= b2 AndAlso b2 <= &HDF)) Then 'EUC_C 'EUC_KANA euc += 2 i += 1 ElseIf i < len - 2 Then b3 = bytes(i + 2) If b1 = &H8F AndAlso (&HA1 <= b2 AndAlso b2 <= &HFE) AndAlso _ (&HA1 <= b3 AndAlso b3 <= &HFE) Then 'EUC_0212 euc += 3 i += 2 End If End If Next For i = 0 To len - 2 b1 = bytes(i) b2 = bytes(i + 1) If (&HC0 <= b1 AndAlso b1 <= &HDF) AndAlso _ (&H80 <= b2 AndAlso b2 <= &HBF) Then 'UTF8 utf8 += 2 i += 1 ElseIf i < len - 2 Then b3 = bytes(i + 2) If (&HE0 <= b1 AndAlso b1 <= &HEF) AndAlso _ (&H80 <= b2 AndAlso b2 <= &HBF) AndAlso _ (&H80 <= b3 AndAlso b3 <= &HBF) Then 'UTF8 utf8 += 3 i += 2 End If End If Next 'M. Takahashi's suggestion 'utf8 += utf8 / 2; System.Diagnostics.Debug.WriteLine( _ String.Format("sjis = {0}, euc = {1}, utf8 = {2}", sjis, euc, utf8)) If euc > sjis AndAlso euc > utf8 Then 'EUC Return System.Text.Encoding.GetEncoding(51932) ElseIf sjis > euc AndAlso sjis > utf8 Then 'SJIS Return System.Text.Encoding.GetEncoding(932) ElseIf utf8 > euc AndAlso utf8 > sjis Then 'UTF8 Return System.Text.Encoding.UTF8 End If Return Nothing End Function /// <summary> /// 文字コードを判別する /// </summary> /// <remarks> /// Jcode.pmのgetcodeメソッドを移植したものです。 /// Jcode.pm(http://openlab.ring.gr.jp/Jcode/index-j.html) /// Jcode.pmのCopyright: Copyright 1999-2005 Dan Kogai /// </remarks> /// <param name="bytes">文字コードを調べるデータ</param> /// <returns>適当と思われるEncodingオブジェクト。 /// 判断できなかった時はnull。</returns> public static System.Text.Encoding GetCode(byte[] bytes) { const byte bEscape = 0x1B; const byte bAt = 0x40; const byte bDollar = 0x24; const byte bAnd = 0x26; const byte bOpen = 0x28; //'(' const byte bB = 0x42; const byte bD = 0x44; const byte bJ = 0x4A; const byte bI = 0x49; int len = bytes.Length; byte b1, b2, b3, b4; //Encode::is_utf8 は無視 bool isBinary = false; for (int i = 0; i < len; i++) { b1 = bytes[i]; if (b1 <= 0x06 || b1 == 0x7F || b1 == 0xFF) { //'binary' isBinary = true; if (b1 == 0x00 && i < len - 1 && bytes[i + 1] <= 0x7F) { //smells like raw unicode return System.Text.Encoding.Unicode; } } } if (isBinary) { return null; } //not Japanese bool notJapanese = true; for (int i = 0; i < len; i++) { b1 = bytes[i]; if (b1 == bEscape || 0x80 <= b1) { notJapanese = false; break; } } if (notJapanese) { return System.Text.Encoding.ASCII; } for (int i = 0; i < len - 2; i++) { b1 = bytes[i]; b2 = bytes[i + 1]; b3 = bytes[i + 2]; if (b1 == bEscape) { if (b2 == bDollar && b3 == bAt) { //JIS_0208 1978 //JIS return System.Text.Encoding.GetEncoding(50220); } else if (b2 == bDollar && b3 == bB) { //JIS_0208 1983 //JIS return System.Text.Encoding.GetEncoding(50220); } else if (b2 == bOpen && (b3 == bB || b3 == bJ)) { //JIS_ASC //JIS return System.Text.Encoding.GetEncoding(50220); } else if (b2 == bOpen && b3 == bI) { //JIS_KANA //JIS return System.Text.Encoding.GetEncoding(50220); } if (i < len - 3) { b4 = bytes[i + 3]; if (b2 == bDollar && b3 == bOpen && b4 == bD) { //JIS_0212 //JIS return System.Text.Encoding.GetEncoding(50220); } if (i < len - 5 && b2 == bAnd && b3 == bAt && b4 == bEscape && bytes[i + 4] == bDollar && bytes[i + 5] == bB) { //JIS_0208 1990 //JIS return System.Text.Encoding.GetEncoding(50220); } } } } //should be euc|sjis|utf8 //use of (?:) by Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp> int sjis = 0; int euc = 0; int utf8 = 0; for (int i = 0; i < len - 1; i++) { b1 = bytes[i]; b2 = bytes[i + 1]; if (((0x81 <= b1 && b1 <= 0x9F) || (0xE0 <= b1 && b1 <= 0xFC)) && ((0x40 <= b2 && b2 <= 0x7E) || (0x80 <= b2 && b2 <= 0xFC))) { //SJIS_C sjis += 2; i++; } } for (int i = 0; i < len - 1; i++) { b1 = bytes[i]; b2 = bytes[i + 1]; if (((0xA1 <= b1 && b1 <= 0xFE) && (0xA1 <= b2 && b2 <= 0xFE)) || (b1 == 0x8E && (0xA1 <= b2 && b2 <= 0xDF))) { //EUC_C //EUC_KANA euc += 2; i++; } else if (i < len - 2) { b3 = bytes[i + 2]; if (b1 == 0x8F && (0xA1 <= b2 && b2 <= 0xFE) && (0xA1 <= b3 && b3 <= 0xFE)) { //EUC_0212 euc += 3; i += 2; } } } for (int i = 0; i < len - 1; i++) { b1 = bytes[i]; b2 = bytes[i + 1]; if ((0xC0 <= b1 && b1 <= 0xDF) && (0x80 <= b2 && b2 <= 0xBF)) { //UTF8 utf8 += 2; i++; } else if (i < len - 2) { b3 = bytes[i + 2]; if ((0xE0 <= b1 && b1 <= 0xEF) && (0x80 <= b2 && b2 <= 0xBF) && (0x80 <= b3 && b3 <= 0xBF)) { //UTF8 utf8 += 3; i += 2; } } } //M. Takahashi's suggestion //utf8 += utf8 / 2; System.Diagnostics.Debug.WriteLine( string.Format("sjis = {0}, euc = {1}, utf8 = {2}", sjis, euc, utf8)); if (euc > sjis && euc > utf8) { //EUC return System.Text.Encoding.GetEncoding(51932); } else if (sjis > euc && sjis > utf8) { //SJIS return System.Text.Encoding.GetEncoding(932); } else if (utf8 > euc && utf8 > sjis) { //UTF8 return System.Text.Encoding.UTF8; } return null; } 次にこのメソッドの使い方を示します。このサンプルでは、TextBox1にテキストファイルのパスを入力し、Button1をクリックすると、テキストファイルの文字コードを調べ、デコードし、RichTextBox1にその内容を表示しています。 'Button1のクリックイベントハンドラ Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'テキストファイルを開く Dim fs As New System.IO.FileStream(TextBox1.Text, _ System.IO.FileMode.Open, System.IO.FileAccess.Read) Dim bs(fs.Length - 1) As Byte 'byte配列に読み込む fs.Read(bs, 0, bs.Length) fs.Close() '文字コードを取得する Dim enc As System.Text.Encoding = GetCode(bs) 'デコードして表示する RichTextBox1.Text = enc.GetString(bs) End Sub //Button1のクリックイベントハンドラ private void Button1_Click(object sender, System.EventArgs e) { //テキストファイルを開く System.IO.FileStream fs = new System.IO.FileStream( TextBox1.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] bs = new byte[fs.Length]; //byte配列に読み込む fs.Read(bs, 0, bs.Length); fs.Close(); //文字コードを取得する System.Text.Encoding enc = GetCode(bs); //デコードして表示する RichTextBox1.Text = enc.GetString(bs); } 第三者の作成したクラス、コードを使う方法G-PROJECTさんが「TextEnc」という文字コードの判別、変換を行うクラスを公開されていました。しかし、現在はサイトが消えています。古いバージョンですが、Internet Archiveのキャッシュが「■G-PROJECT■ -文字コード判別・変換クラス(C#)」にあります。 さらに雅階凡さんが「文字コードの判定」で文字コードの判定に関する詳しい説明と、サンプルコードを公開されています。 「NonSoft - 文字コード判定/変換DLL(VB6/VB.NET/C#.NET)」では、文字コードを判定できるDLLが公開されています。 「Windows Developerマガジン2006/1月号」の「文字コードの自動判別機能実装」のサンプルにも文字コードを判別するコードが紹介されています。 mlang.dllを使う方法外部DLLに頼る方法としては、mlang.dllのIMultiLanguage2::DetectInputCodepageを使用する方法があります。文字コードの判別が必要な大半のアプリで、これが使われているのではないかと思います。この方法は、Internet Explorer 5以上で使用できます。 以下に.NETでIMultiLanguage2::DetectInputCodepageメソッドを使うための方法を簡単に説明します。 mlang.dllを使うため、Visual Studioの「参照の追加」でCOMを探してみても、mlang.dllは通常見つかりません。これは、mlang.dllにタイプライブラリがないためです。よってまず"midl.exe"を使用して、"MLang.Idl"から"MLang.tlb"を作成し、これを"regtlib.exe"を使って登録します。 "MIDL.EXE"のパスは、Visual Studio .NET 2003ならば「C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Tools\Bin\Midl.Exe」、Visual Studio 2008ならば「C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\midl.exe」のようになるようです。 "MLang.Idl"のパスは、Visual Studio .NET 2003ならば「C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\Include\MLang.Idl」、Visual Studio 2008ならば「C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\MLang.Idl」のようになるようです。 midl.exe MLang.Idl とすれば、タイプライブラリ"MLang.tlb"がカレントディレクトリに作成されます(上記のコマンドラインではディレクトリを省略しています)。
注意:midl.exeで「midl : command line error MIDL1005 : cannot find C preprocessor cl.exe」のようなエラーが出る場合は、cl.exeにパスを通すか、「コマンド ライン ビルドのパスと環境変数の設定」で紹介されているように、まずvcvars32.bat(もしくは、Vcvarsall.bat)を実行してください。
"regtlib.exe"のパスは、Visual Studio .NET 2003ならば「C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\Include\regtlib.exe」ですが、Visual Studio 2005からは"regtlib.exe"の代わりに「C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regtlibv12.exe」が同じように使えます。 regtlib.exe MLang.tlb とすれば、MLang.tlbを登録できます(上記のコマンドラインではディレクトリを省略しています)。
補足:登録を解除するときは、"-u"パラメータを付けます。
これで「参照の追加」の「COM」で"mlang.dll"(MultiLanguage Object Model)を選択できるようになります。
補足:Visual Studioを使わない場合は、"Tlbimp.exe"を使ってinterop assembly(相互運用機能アセンブリ)を作成できます。
これで、DetectInputCodepageメソッドを使う準備ができました。次にDetectInputCodepageメソッドを使って文字コードを判別するサンプルを紹介します。このサンプルでも先と同じく、TextBox1にテキストファイルのパスを入力し、Button1をクリックすると、テキストファイルの文字コードを調べ、デコードし、RichTextBox1にその内容を表示しています。 'Button1のクリックイベントハンドラ Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'テキストファイルを開く Dim fs As New System.IO.FileStream(TextBox1.Text, _ System.IO.FileMode.Open, System.IO.FileAccess.Read) Dim bs(fs.Length - 1) As Byte 'byte配列に読み込む fs.Read(bs, 0, bs.Length) fs.Close() '文字コードを判別する Dim enc As System.Text.Encoding = DetectEncoding(bs) 'デコードして表示する RichTextBox1.Text = enc.GetString(bs) End Sub ''' <summary> ''' IMultiLanguage2.DetectInputCodepageを使って文字コードを判別する ''' </summary> ''' <param name="sbyts">文字コードを調べるデータ</param> ''' <returns>適当と思われるEncodingオブジェクト。</returns> Public Shared Function DetectEncoding(ByVal bytes As Byte()) As System.Text.Encoding '準備 'sbyte型配列に変換する 'Dim sbyts(bytes.Length - 1) As System.SByte 'System.Buffer.BlockCopy(bytes, 0, sbyts, 0, bytes.Length) Dim sbyts As SByte() = DirectCast(DirectCast(bytes, Object), SByte()) Dim len As Integer = sbyts.Length Dim ml As MultiLanguage.IMultiLanguage2 = New MultiLanguage.CMultiLanguageClass() '取得する候補(tagDetectEncodingInfo)の数 Dim scores As Integer = 1 Dim detects As MultiLanguage.tagDetectEncodingInfo() = _ New MultiLanguage.tagDetectEncodingInfo(scores - 1) {} '文字コードを判別 ml.DetectInputCodepage(0, 0, sbyts(0), len, detects(0), scores) '一番初めのtagDetectEncodingInfoのEncodingを取得 'detectsはnDocPercentの大きい順番に並んでいる? Dim enc As System.Text.Encoding = _ System.Text.Encoding.GetEncoding(CInt(detects(0).nCodePage)) '後始末 System.Runtime.InteropServices.Marshal.ReleaseComObject(ml) Return enc End Function //Button1のクリックイベントハンドラ private void Button1_Click(object sender, System.EventArgs e) { //テキストファイルを開く System.IO.FileStream fs = new System.IO.FileStream( TextBox1.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] bs = new byte[fs.Length]; //byte配列に読み込む fs.Read(bs, 0, bs.Length); fs.Close(); //文字コードを判別する System.Text.Encoding enc = DetectEncoding(bs); //デコードして表示する RichTextBox1.Text = enc.GetString(bs); } /// <summary> /// IMultiLanguage2.DetectInputCodepageを使って文字コードを判別する /// </summary> /// <param name="sbyts">文字コードを調べるデータ</param> /// <returns>適当と思われるEncodingオブジェクト。</returns> public static System.Text.Encoding DetectEncoding(byte[] bytes) { //準備 //sbyte型配列に変換する //sbyte[] sbyts = new sbyte[bs.Length]; //System.Buffer.BlockCopy(bs, 0, sbyts, 0, bs.Length); sbyte[] sbyts = (sbyte[])(object)bytes; int len = sbyts.Length; MultiLanguage.IMultiLanguage2 ml = new MultiLanguage.CMultiLanguageClass(); //取得する候補(tagDetectEncodingInfo)の数 int scores = 1; MultiLanguage.tagDetectEncodingInfo[] detects = new MultiLanguage.tagDetectEncodingInfo[scores]; //文字コードを判別 ml.DetectInputCodepage( 0, 0, ref sbyts[0], ref len, ref detects[0], ref scores); //一番初めのtagDetectEncodingInfoのEncodingを取得 //detectsはnDocPercentの大きい順番に並んでいる? System.Text.Encoding enc = System.Text.Encoding.GetEncoding((int)detects[0].nCodePage); //後始末 System.Runtime.InteropServices.Marshal.ReleaseComObject(ml); return enc; } scoresを1より大きくすると、DetectInputCodepageメソッドにより複数の候補が返されることがあります。候補の数はscoresに入り、その数だけdetectsの要素に入ります。候補の内どれが有力かは、tagDetectEncodingInfoのnDocPercentやnConfidenceで判断します。nDocPercentが一番高い候補がdetects[0]に入るようです。
(この記事は、「.NETプログラミング研究 第43号」で紹介したものを基にしています。) 注意:この記事では、基本的な事柄の説明が省略されているかもしれません。初心者の方は、特に以下の点にご注意ください。 |
|
Copyright(C) DOBON!. All rights reserved.
|