-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageScanner.cs
357 lines (318 loc) · 8.85 KB
/
ImageScanner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Drawing;
using Windows.Devices.Enumeration;
using Windows.Devices.Scanners;
using Windows.Graphics.Imaging;
using Windows.Storage;
namespace Produire.PImaging
{
public class スキャナ : IProduireStaticClass
{
ImageScanner myScanner;
CancellationTokenSource cancellationToken;
DeviceWatcher scannerWatcher;
List<DeviceInformation> scannerList = new List<DeviceInformation>();
#region 手順
/// <summary>
/// 利用できるイメージスキャナを列挙します
/// </summary>
[自分を]
public void 列挙する()
{
scannerWatcher = DeviceInformation.CreateWatcher(DeviceClass.ImageScanner);
scannerWatcher.Added += OnScannerAdded;
scannerWatcher.Removed += OnScannerRemoved;
scannerWatcher.EnumerationCompleted += OnScannerEnumerationComplete;
scannerWatcher.Start();
for (; ; )
{
if (scannerWatcher.Status == DeviceWatcherStatus.EnumerationCompleted
|| scannerWatcher.Status == DeviceWatcherStatus.Stopped) break;
Task t1 = null;
Task.Run(() =>
{
t1 = Task.Delay(500);
}).Wait();
}
}
private void OnScannerAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
{
foreach (var item in scannerList)
{
if (item.Id == deviceInfo.Id)
{
return;
}
}
if (deviceInfo != null) scannerList.Add(deviceInfo);
}
private void OnScannerRemoved(DeviceWatcher sender, DeviceInformationUpdate args)
{
int i = 0;
for (; i < scannerList.Count; i++)
{
if (scannerList[i].Id == args.Id)
{
scannerList.RemoveAt(i);
break;
}
}
}
private void OnScannerEnumerationComplete(DeviceWatcher sender, object args)
{
scannerWatcher.Stop();
}
/// <summary>
/// 読み取りに使用するイメージスキャナを選択します。
/// </summary>
/// <param name="デバイス名"></param>
/// <returns></returns>
[自分へ]
public bool 選択する([を]string デバイス名)
{
if (string.IsNullOrEmpty(デバイス名)) throw new ProduireException("スキャナのデバイスIDまたは名称を指定してください。");
string deviceId = null;
foreach (var item in scannerList)
{
if (item.Id == デバイス名)
{
deviceId = item.Id;
break;
}
}
if (deviceId == null)
{
foreach (var item in scannerList)
{
if (item.Name == デバイス名)
{
deviceId = item.Id;
break;
}
}
}
if (deviceId == null)
{
throw new ProduireException("該当するスキャナが見つかりません。" + デバイス名);
}
Task<ImageScanner> t1 = null;
Task.Run(() =>
{
try
{
t1 = ImageScanner.FromIdAsync(deviceId).AsTask<ImageScanner>();
}
catch (Exception ex)
{
if (ex.InnerException != null) throw ex.InnerException;
throw;
}
}).Wait();
myScanner = t1.Result;
return myScanner != null;
}
/// <summary>
/// イメージスキャナから画像を読み取って指定したフォルダへ保存します。
/// </summary>
/// <param name="パス">保存先のフォルダ</param>
/// <returns>保存した画像ファイル</returns>
[自分から]
public string[] 読み取る([へ, 省略]string パス)
{
if (myScanner == null)
{
string deviceId = GetDefaultDevice();
選択する(deviceId);
}
cancellationToken = new CancellationTokenSource();
ImageScannerScanResult result;
Task<ImageScannerScanResult> t1 = null;
Task.Run(() =>
{
t1 = ScanFilesToFolder();
}).Wait();
result = t1.Result;
if (!string.IsNullOrEmpty(パス) && !Directory.Exists(パス)) Directory.CreateDirectory(パス);
List<string> list = new List<string>();
foreach (StorageFile file in result.ScannedFiles)
{
string path = Path.Combine(パス, Path.GetFileName(file.Path));
if (file.Path != path) File.Move(file.Path, path);
list.Add(path);
}
return list.ToArray();
}
private async Task<ImageScannerScanResult> ScanFilesToFolder()
{
StorageFolder folder = KnownFolders.PicturesLibrary;
if (folder == null) return null;
ImageScannerScanSource source = ImageScannerScanSource.AutoConfigured;
if (selectedSource != -1)
{
source = 読み取り元;
if (!myScanner.IsScanSourceSupported(source))
{
throw new ProduireException("この読み取り元はサポートされていません。");
}
}
else if (myScanner.IsScanSourceSupported(ImageScannerScanSource.AutoConfigured))
{
source = ImageScannerScanSource.AutoConfigured;
}
else
{
source = ImageScannerScanSource.Default;
}
return await myScanner.ScanFilesToFolderAsync(source, folder).AsTask(cancellationToken.Token);
}
/// <summary>
/// イメージスキャナからプレビュー用の画像を読み取り画像として返します。
/// </summary>
/// <returns>画像</returns>
[自分から]
public Image プレビュー()
{
if (myScanner == null)
{
string deviceId = GetDefaultDevice();
選択する(deviceId);
}
cancellationToken = new CancellationTokenSource();
Image result;
Task<Image> t1 = null;
Task.Run(() =>
{
t1 = SavePreview();
}).Wait();
try
{
result = t1.Result;
}
catch (Exception ex)
{
if (ex.InnerException != null) throw ex.InnerException;
throw;
}
return result;
}
private async Task<Image> SavePreview()
{
Image image = null;
ImageScannerPreviewResult result = null;
using (MemoryStream netStream = new MemoryStream())
{
var scanStream = WindowsRuntimeStreamExtensions.AsRandomAccessStream(netStream);
ImageScannerScanSource source = ImageScannerScanSource.AutoConfigured;
if (selectedSource != -1)
{
source = 読み取り元;
if (!myScanner.IsScanSourceSupported(source))
{
throw new ProduireException("この読み取り元はサポートされていません。");
}
}
else if (myScanner.IsScanSourceSupported(ImageScannerScanSource.AutoConfigured))
{
source = ImageScannerScanSource.AutoConfigured;
}
else
{
source = ImageScannerScanSource.Default;
}
result = await myScanner.ScanPreviewToStreamAsync(source, scanStream);
await scanStream.FlushAsync();
scanStream.Seek(0);
var decoder = await BitmapDecoder.CreateAsync(scanStream);
var data = await decoder.GetPixelDataAsync();
using (MemoryStream netStream2 = new MemoryStream())
{
var bmpStream = WindowsRuntimeStreamExtensions.AsRandomAccessStream(netStream2);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, bmpStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)decoder.PixelWidth, (uint)decoder.PixelHeight,
decoder.DpiX, decoder.DpiY, data.DetachPixelData());
encoder.BitmapTransform.Bounds = new BitmapBounds() { Width = decoder.PixelWidth, Height = decoder.PixelHeight };
await encoder.FlushAsync();
bmpStream.Seek(0);
image = Image.FromStream(netStream2);
}
}
return image;
}
private string GetDefaultDevice()
{
if (scannerList.Count == 0) 列挙する();
foreach (var item in scannerList)
{
if (item.IsDefault) return item.Id;
}
if (scannerList.Count > 0) return scannerList[0].Id;
return null;
}
public void CancelScanning()
{
if (cancellationToken != null)
{
cancellationToken.Cancel();
}
}
#endregion
#region 設定項目
/// <summary>
/// 利用できるイメージスキャナのデバイス名一覧を返します
/// </summary>
public string[] 一覧
{
get
{
if (scannerList.Count == 0) 列挙する();
List<string> list = new List<string>();
foreach (var item in scannerList)
{
list.Add(item.Name);
}
return list.ToArray();
}
}
/// <summary>
/// 利用できるイメージスキャナのデバイスID一覧を返します
/// </summary>
public string[] デバイスID一覧
{
get
{
if (scannerList.Count == 0) 列挙する();
List<string> list = new List<string>();
foreach (var item in scannerList)
{
list.Add(item.Id);
}
return list.ToArray();
}
}
int selectedSource = -1;
/// <summary>
/// 読み取りに使用するソース
/// </summary>
public ImageScannerScanSource 読み取り元
{
get { return selectedSource == -1 ? ImageScannerScanSource.AutoConfigured : (ImageScannerScanSource)selectedSource; }
set { selectedSource = (int)value; }
}
#endregion
}
[列挙体(typeof(ImageScannerScanSource))]
public enum 読み取り元列挙
{
既定 = ImageScannerScanSource.Default,
フィーダ = ImageScannerScanSource.Feeder,
フラットヘッド = ImageScannerScanSource.Flatbed,
自動 = ImageScannerScanSource.AutoConfigured
}
}