WPF 应用程序中的 WIA 扫描
Posted
技术标签:
【中文标题】WPF 应用程序中的 WIA 扫描【英文标题】:WIA scanning in a WPF application 【发布时间】:2012-02-14 02:16:39 【问题描述】:我正在使用 WIA 2.0 从 HP 扫描仪扫描图像。问题是保存的 TIFF 大约 9MB 大(300dpi 的 A4 页面,灰度)。我将包含 TIFF 格式扫描的 WIA 的 ImageFile 转换为 BitmapSource,如下所示:
public static BitmapSource ConvertScannedImage(ImageFile imageFile)
if (imageFile == null)
return null;
// save the image out to a temp file
string fileName = Path.GetTempFileName();
// this is pretty hokey, but since SaveFile won't overwrite, we
// need to do something to both guarantee a unique name and
// also allow SaveFile to write the file
File.Delete(fileName);
// now save using the same filename
imageFile.SaveFile(fileName);
BitmapFrame img;
// load the file back in to a WPF type, this is just
// to get around size issues with large scans
using (FileStream stream = File.OpenRead(fileName))
img = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
stream.Close();
// clean up
File.Delete(fileName);
return img;
任何人都知道如何减小图像大小,如果可能的话在内存中(因为我有一些可以预览和旋转的扫描)?谢谢。
【问题讨论】:
顺便说一句,没有必要关闭 using 块内的流,因为在处理过程中流会自动关闭。 【参考方案1】:使用压缩。本例 Ccitt4 用于黑白传真压缩,压缩系数很大,但如果要保持灰度,还有其他版本。
using System.Windows.Media.Imaging;
public static byte[] ConvertBitmapSourceToByteArray(BitmapSource imageToConvert, ImageFormat formatOfImage)
byte[] buffer;
try
using (var ms = new MemoryStream())
switch (formatOfImage)
case ImageFormat.Png:
var bencoder = new PngBitmapEncoder();
bencoder.Frames.Add(BitmapFrame.Create(imageToConvert));
bencoder.Save(ms);
break;
case ImageFormat.Tiff:
var tencoder = new TiffBitmapEncoder();
tencoder.Compression = TiffCompressOption.Ccitt4;
tencoder.Frames.Add(BitmapFrame.Create(imageToConvert));
tencoder.Save(ms);
break;
ms.Flush();
buffer = ms.GetBuffer();
catch (Exception) throw;
return buffer;
然后写图片
doc.SaveDirectory = DestinationDirectoryImages;
doc.Filename = fName;
doc.Image = ImageConversion.ConvertBitmapSourceToByteArray(img.Image, ImageFormat.Tiff);
.Image 的实现是……
private byte[] _image;
/// <summary>
/// Bytes for Image. Set to null to delete related file.
/// </summary>
public virtual byte[] Image
get
if (_image == null)
if (SaveDirectory == null) throw new ValidationException("SaveDirectory not set for DriverDoc");
string fullFilename = Path.Combine(SaveDirectory, Filename);
if (!string.IsNullOrEmpty(fullFilename))
if (File.Exists(fullFilename))
_image = File.ReadAllBytes(fullFilename);
else
_image = File.ReadAllBytes("Resources\\FileNotFound.bmp");
return _image;
set
if (_image == value) return;
_image = value;
if (SaveDirectory == null) throw new ValidationException("SaveDirectory not set for DriverDoc");
string fullFilename = Path.Combine(SaveDirectory, Filename);
if (_image != null)
if (!string.IsNullOrEmpty(fullFilename))
_image = value;
File.WriteAllBytes(fullFilename, _image);
else
if (!string.IsNullOrEmpty(Filename) && File.Exists(fullFilename))
File.Delete(fullFilename);
【讨论】:
以上是关于WPF 应用程序中的 WIA 扫描的主要内容,如果未能解决你的问题,请参考以下文章