2025-10-28 09:29:53 +09:00

123 lines
4.8 KiB
C#

using FY2526_SW_PoC_APIRelay;
using ImageMagick;
using PretreatmentFile;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage;
using Windows.Storage.Streams;
namespace PretreatmentFile
{
public class OcrHelper
{
/// <summary>OCR</summary>
/// <param name="filePath">ファイルパス</param>
/// <returns>読み取った文字列</returns>
///
public static async Task<string?> Ocr(string filePath)
{
try
{
string extension = Path.GetExtension(filePath).ToLower();
string? convertedFilePath = null;
if (extension == ".heic")
{
try
{
convertedFilePath = ConvertHeicToJpeg(filePath);
if (convertedFilePath == null)
{
LogWriter.WriteLog("HEICファイルの変換に失敗しました", LogWriter.LogLevel.ERROR);
return null;
}
filePath = convertedFilePath;
}
catch (Exception conversionException)
{
LogWriter.WriteLog($"HEICからJPEGへの変換中にエラーが発生しました: {conversionException.Message}", LogWriter.LogLevel.ERROR);
return null;
}
}
// ファイルを開き、BitmapDecoderを作成
var file = await StorageFile.GetFileFromPathAsync(filePath);
var stream = await file.OpenAsync(FileAccessMode.Read);
var decoder = await BitmapDecoder.CreateAsync(stream);
var bmp = await decoder.GetSoftwareBitmapAsync();
try
{
var engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("ja"));
if (engine != null)
{
var result = await engine.RecognizeAsync(bmp);
// OcrResult.Lines から各行のテキストを取得し、改行で結合
var extractedText = string.Join(Environment.NewLine, result.Lines.Select(line => line.Text));
if (convertedFilePath != null && File.Exists(convertedFilePath))
{
try
{
File.Delete(convertedFilePath); // JPEGファイルを削除
}
catch (Exception deleteException)
{
LogWriter.WriteLog($"JPEGファイルの削除に失敗しました: {deleteException.Message}", LogWriter.LogLevel.ERROR);
}
}
return extractedText;
}
else
{
LogWriter.WriteLog("OCRエンジンの作成に失敗しました", LogWriter.LogLevel.ERROR);
return null;
}
}
catch (Exception ocrException)
{
LogWriter.WriteLog($"OCR認識に失敗しました: {ocrException.Message}", LogWriter.LogLevel.ERROR);
return null;
}
}
catch (Exception e)
{
LogWriter.WriteLog($"予期しないエラーが発生しました: {e.Message}", LogWriter.LogLevel.ERROR);
return null;
}
}
/// <summary>heicをjpegに変換する</summary>
/// <param name="heicFilePath">heicファイルのパス</param>
/// <returns>変換後のjpegファイルのパス</returns>
///
private static string? ConvertHeicToJpeg(string heicFilePath)
{
try
{
// Magick.NETを使用してHEICファイルをJPEGに変換
string outputFilePath = heicFilePath.Replace(".heic", ".jpg", StringComparison.OrdinalIgnoreCase);
using (var image = new MagickImage(heicFilePath))
{
// JPEGとして保存
image.Format = MagickFormat.Jpeg;
image.Write(outputFilePath);
}
return outputFilePath;
}
catch (Exception e)
{
LogWriter.WriteLog($"HEICファイルの変換中にエラーが発生しました: {e.Message}", LogWriter.LogLevel.ERROR);
return null; // 変換に失敗した場合はnullを返す
}
}
}
}