我有一個應用程式正在讀取影像的登記牌。我有一個簡單的 UI,用戶可以在其中選擇要使用 FilePicker 掃描的影像。
所以出現問題的場景
- 選擇影像 A
- 掃描影像 A --> 成功
- 選擇影像 B
- 掃描影像 B --> 成功
- 選擇影像 A
- 掃描影像 A --> 失敗
我收到的錯誤
System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI .'
我正在使用 WPF,因此 Image 組件SourceImage用作源。然后我進行轉換。我找不到要轉換的東西,SourceImage --> SoftwareBitmap所以我Bitmap用作proxy物件
SourceImage --> Bitmap --> SoftwareImage (used by Microsoft OCR)
代碼示例
檔案選擇器
OpenFileDialog openFileDialog = new OpenFileDialog()
{
InitialDirectory = @"c:\Temp",
Filter = "Image files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png",
FilterIndex = 0,
RestoreDirectory = true,
Multiselect = false
};
if (openFileDialog.ShowDialog() == true)
{
img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = new Uri(openFileDialog.FileName);
img.EndInit();
if(img != null)
{
ANPR_image.Source = img;
}
}
轉換為位圖
Bitmap bmp = new Bitmap(
source.PixelWidth,
source.PixelHeight,
System.Drawing.Imaging.PixelFormat.Format32bppArgb
);
BitmapData data = bmp.LockBits(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
source.CopyPixels(
Int32Rect.Empty,
data.Scan0,
data.Height * data.Stride,
data.Stride);
bmp.UnlockBits(data);
return bmp;
轉換為 SoftwareBitmap 和 OCR
using (Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
{
if(newBitmap != null)
{
newBitmap.Save(stream.AsStream(), ImageFormat.Tiff); //choose the specific image format by your own bitmap source
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
using (SoftwareBitmap s_Bitmap = await decoder.GetSoftwareBitmapAsync())
{
try
{
result = await ocr.RecognizeAsync(s_Bitmap);
newBitmap.Dispose();
image.Dispose();
return result is null ? "" : result.Text;
}
catch(Exception e)
{
return "Error";
}
}
}
else
{
return "Image is null";
}
錯誤發生在這里newBitmap.Save(stream.AsStream(), ImageFormat.Tiff); //choose the specific image format by your own bitmap source
我在網上閱讀了有關此錯誤的資訊,似乎某處可能有鎖,但我不知道在哪里...我嘗試處理所有可能的影像,并用using陳述句包裝了所有內容。沒有任何作用...
任何想法,建議將不勝感激!
謝謝
uj5u.com熱心網友回復:
您可以通過從單個MemoryStream. 傳遞stream.AsRandomAccessStream()給 BitmapDecoder。
var buffer = await File.ReadAllBytesAsync(openFileDialog.FileName);
using (var stream = new MemoryStream(buffer))
{
ANPR_image.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
using (var randomAccessStream = stream.AsRandomAccessStream())
{
Windows.Graphics.Imaging.BitmapDecoder decoder =
await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(
randomAccessStream);
using (var softwareBitmap = await decoder.GetSoftwareBitmapAsync())
{
// ...
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486021.html
上一篇:WPF:根據WPFDatagrid中的列索引設定特定列的單元格的背景顏色
下一篇:WPF:畫布,影片矩形
