ステップ記録ツールで作成したMHTファイルから画像(JPG)を抽出するソース
2024-04-06 23:11:10
private void btnCreateImage_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "MHT files (*.mht)|*.mht|All files (*.*)|*.*";
openFileDialog.Title = "Select MHT file to extract images";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string mhtFilePath = openFileDialog.FileName;
string imgFolderName = Path.GetFileNameWithoutExtension(mhtFilePath); // MHT ファイル名(拡張子無し)をフォルダ名として使用
string imgFolderPath = Path.Combine(Path.GetDirectoryName(mhtFilePath), imgFolderName); // MHT ファイルと同じ場所にフォルダを作成
ExtractImagesFromMHT(mhtFilePath, imgFolderPath);
MessageBox.Show("Images extracted successfully!");
}
else
{
MessageBox.Show("No file selected.");
}
}
private void ExtractImagesFromMHT(string mhtFilePath, string imgFolderPath)
{
// フォルダが存在しない場合は作成する
if (!Directory.Exists(imgFolderPath))
{
Directory.CreateDirectory(imgFolderPath);
}
string mhtContent = File.ReadAllText(mhtFilePath);
// 画像の BASE64 エンコードされたデータを抽出する正規表現パターン
string pattern = @"Content-Type: image/(?<type>.*?).*?Content-Transfer-Encoding: base64.*?\r\n\r\n(?<data>.*?)--";
MatchCollection matches = Regex.Matches(mhtContent, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
// 画像データをファイルに保存
int count = 1;
foreach (Match match in matches)
{
//string imageType = match.Groups["type"].Value;
string imageType = "jpg";
string imageData = match.Groups["data"].Value;
// 画像ファイル名を作成
string imgFileName = $"image_{count++}.{imageType}"; // 画像ファイル名を適切に指定してください
string imgFilePath = Path.Combine(imgFolderPath, imgFileName);
// BASE64 データをデコードして画像ファイルに保存
byte[] imgBytes = Convert.FromBase64String(imageData);
File.WriteAllBytes(imgFilePath, imgBytes);
}
}
Copyright © 2024 OpenAI