我正在处理一个需要使用OCR处理文件的项目,
由于我不允许直接在UWP中访问文件,因此我只有两个选择:
文件选择器(不需要的),或从Http服务器获取文件,
我能够使用文件选择器,这是我的实现:
SoftwareBitmap softwareBitmap;
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.FileTypeFilter.Add(".jpg");
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
var inputFile = await fileOpenPicker.PickSingleFileAsync();
using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
}
OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("fr-FR"));
OcrResult ocrResults = await ocrEngine.RecognizeAsync(softwareBitmap);
OcrLine ocrResult = ocrResults.Lines[0];
string text = ocrResult.Text;
现在我尝试从HTTP GET请求中获取文件,但我无法弄清楚如何以SoftwareBitmap
格式(OcrEngine
接受)
来自link,我找到了这个有用的代码示例,我以BitmapImage
格式获取文件
private async void Populate()
{
string QRServiceAPI = "https://api.qrserver.com/v1/create-qr-code/?data={0}&size={1}x{2}";
string q = string.Format(QRServiceAPI, "http://solatys.com", 150, 150);
using (var d = new Downloader())
{
var feed = await d.GetDataFeed(q);
feed.Seek(0, SeekOrigin.Begin);
BitmapImage bmp = new BitmapImage();
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])feed.ToArray());
writer.StoreAsync().GetResults();
}
var image = new BitmapImage();
image.SetSource(ms);
Image1.Source = image;
}
}
}
如何将此BitmapImage
转换为SoftwareBitmap
,我该怎么办?
或者如何直接将其作为SoftwareBitmap
?
答案 0 :(得分:2)
您可以通过使用HttpClient获取图像并将内容流转换为IRandomAccessStream来实现此目的
HttpClient client = new HttpClient();
var response = await client.GetAsync("http://my.image");
var stream = await response.Content.ReadAsStreamAsync();
IRandomAccessStream randomAccessStream = stream.AsRandomAccessStream();
从那里它和你已经拥有的一样
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
请注意,AsRandomAccessStream
是System.IO
命名空间中的扩展方法。