using Saraff.Twain;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WIA;
namespace HXX.Scanner.Biz
{
///
/// 扫描仪,根据老类修改而来,很多方法没用
///
public class Device_Scanner
{
public Device_Scanner(DeviceInfo deviceInfo)
{
this._deviceInfo = deviceInfo;
this.manufacturer = (string)deviceInfo.Properties["Manufacturer"].get_Value();
}
public Device_Scanner(string deviceName)
{
this.isTwain = true;
this.deviceName = deviceName;
if (deviceName.ToLower().Contains("canon"))
{
this.manufacturer = "CANON";
}
else if (deviceName.ToLower().Contains("panasonic"))
{
this.manufacturer = "Panasonic";
}
else if (deviceName.ToLower().Contains("kodak"))
{
this.manufacturer = "Kodak";
}
else if (deviceName.ToLower().Contains("epson"))
{
this.manufacturer = "Epson";
}
else if (deviceName.ToLower().Contains("hp"))
{
this.manufacturer = "HP";
}
else if (deviceName.ToLower().Contains("huago"))
{
this.manufacturer = "HUAGO";
}
else
{
this.manufacturer = "";
}
}
///
/// 是否被激活
///
public int isActive = 0;
///
/// 是否支持tw,废弃
///
public Boolean isTwain = false;
///
/// 名称
///
public string deviceName;
///
/// 制造商
///
public string manufacturer;
///
/// 分辨率
///
public int resolution = 200;
///
/// 亮度
///
public int ld = 0;
///
/// 对比度
///
public int dbd = 0;
///
/// 纸张规格
///
public PaperSize zz = PaperSize.A3;
///
/// wia使用,废弃
///
public readonly DeviceInfo _deviceInfo;
///
/// 废弃
///
public int width_pixel = (int)Math.Ceiling(200 * 297 / 25.4); //默认A3
///
/// 废弃
///
public int height_pixel = (int)Math.Ceiling(200 * 420 / 25.4);
///
/// 废弃
///
public int colorMode = 65536 * 2;
///
/// 废弃
///
//这个参数暂时没用,WIA.WiaImageIntent.GrayscaleIntent.GetHashCode();//1; //
public Boolean duplex = true;
///
/// 下标
///
public int dsIndex { get; set; }
///
/// 废弃
///
public Twain32.Enumeration Brightness;
///
/// 废弃
///
public int BrightnessBaseIndex = 0;
///
/// 废弃
///
public Twain32.Enumeration Contrasts;
///
/// 废弃
///
public int ContrastsBaseIndex = 0;
///
/// 废弃
///
public bool openSourceReady = false;
///
/// 废弃
///
public bool isChoose = false;
///
/// 设置纸张,会顺便设置宽高
///
///
public void setPaperSize(PaperSize zz)
{
this.zz = zz;
int wMM = 210;
int hMM = 297;
if (this.zz == PaperSize.A4) { wMM = 210; hMM = 297; }
else if (this.zz == PaperSize.A3) { wMM = 297; hMM = 420; }
else if (this.zz == PaperSize.K16) { wMM = 195; hMM = 270; }
else if (this.zz == PaperSize.K8) { wMM = 270; hMM = 390; }
this.width_pixel = (int)Math.Ceiling(this.resolution * wMM / 25.4);
this.height_pixel = (int)Math.Ceiling(this.resolution * hMM / 25.4);
}
///
/// 压缩,约65倍
///
///
///
///
public static void zipImage(string src, string dst, bool delSrc)
{
EncoderParameters eps = new EncoderParameters(1);
//黑白压缩
//eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
//灰度压缩
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW);
Bitmap bi = new Bitmap(src);
ImageCodecInfo ici = GetEncoderInfo("image/tiff");
bi.Save(dst, ici, eps);
bi.Dispose();
bi = null;
if (delSrc)
{
File.Delete(src);
}
}
///
/// 压缩,约65倍
///
///
///
///
public static void zipImage_jpeg(string src, string dst, bool delSrc)
{
EncoderParameters eps = new EncoderParameters(1);
//黑白压缩
//eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
//灰度压缩
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW);
Bitmap bi = new Bitmap(src);
ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
bi.Save(dst, ici, eps);
bi.Dispose();
bi = null;
if (delSrc)
{
File.Delete(src);
}
}
public ImageFile ScanTIFFTest(string dir, string test)
{
var device = this._deviceInfo.Connect();
//device.Propertiesf
SetWIAProperty(device.Properties, WiaPropertyConstant.DocumentHandlingSelect, 5);
SetWIAProperty(device.Properties, WiaPropertyConstant.Pages, 1);
//if (duplex)
//{
// device.Properties["Document Handling Select"].set_Value(37);
// //device.Properties["Pages"].set_Value(1);
//}
//else
//{
// device.Properties["Document Handling Select"].set_Value(1); //默认
// //device.Properties["Pages"].set_Value(1); //默认
//}
CommonDialogClass dlg = new CommonDialogClass();
//新扫描界面
//dlg.ShowAcquisitionWizard(device);
//你想扫描什么界面
//ImageFile imageF = dlg.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, WIA.FormatID.wiaFormatTIFF, false, true) as ImageFile;
//显示设备选择界面
//var deviceTemp = dlg.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, true);
//你想扫描什么界面
//Items items = dlg.ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, true);
//显示设备属性
//dlg.ShowDeviceProperties(device, true);
//var item = device.Items[1];//index是从1开始的,而不是从0
//显示扫描属性:亮度、对比度、DPI、颜色模式
//dlg.ShowItemProperties(item, true);
//显示完成百分比
//var trans = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatTIFF, true);
//Items items = dlg.ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, false, true, false);
//MessageBox.Show(items.Count.ToString());
//foreach (Item it in items)
//{
// AdjustScannerSettings(it, resolution, 0, 0, width_pixel, height_pixel, ld, dbd, colorMode);
// CommonDialogClass dlgTemp = new CommonDialogClass();
// ImageFile imageFile = dlgTemp.ShowTransfer(
// it,
// WIA.FormatID.wiaFormatTIFF,
// true)
// as ImageFile;
// if (imageFile != null)
// {
// string tmpFile = dir + "\\_tmp" + DateTime.Now.ToString("MMddHHmmssfff") + ".tif";
// string testFileName2 = dir + "\\测试" + DateTime.Now.ToString("MMddHHmmssfff") + "_A.tif";
// imageFile.SaveFile(tmpFile);
// zipImage(tmpFile, testFileName2, true);
// }
//}
var item = device.Items[1];//index是从1开始的,而不是从0
try
{
AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, ld, dbd, colorMode);
if (true)
{
//第一面
var imageFile = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatTIFF, true) as ImageFile;
if (imageFile != null)
{
string tmpFile = dir + "\\_tmp" + DateTime.Now.ToString("MMddHHmmssfff") + ".tif";
string testFileName2 = dir + "\\测试" + DateTime.Now.ToString("MMddHHmmssfff") + "_A.tif";
imageFile.SaveFile(tmpFile);
zipImage(tmpFile, testFileName2, false);
}
}
if (duplex)
{
//第二面
ImageFile imageFile2 = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatTIFF, true) as ImageFile;
if (imageFile2 != null)
{
string tmpFile = dir + "\\_tmp" + DateTime.Now.ToString("MMddHHmmssfff") + ".tif";
string testFileName2 = dir + "\\测试" + DateTime.Now.ToString("MMddHHmmssfff") + "_B.tif";
imageFile2.SaveFile(tmpFile);
zipImage(tmpFile, testFileName2, false);
}
}
//打开扫描文件夹
System.Diagnostics.Process.Start("explorer.exe", dir);
return null;//return imageFile;
}
catch (COMException e)
{
Console.WriteLine(e.ToString());
Console.WriteLine(e.ErrorCode);
Console.WriteLine(e.Message);
uint errorCode = (uint)e.ErrorCode;
if (errorCode == 0x80210006)
{
MessageBox.Show("扫描仪状态错误");
}
else if (errorCode == 0x80210064)
{
MessageBox.Show("取消扫描");
}
else if (errorCode == 0x80210003)
{
MessageBox.Show("请放入要扫描的纸张");
}
else
{
//MessageBox.Show("未知错误", "Error", MessageBoxButtons.OK);
throw e;
}
}
return new ImageFile();
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; j++)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
}
private static void showPropValues(IProperties ps)
{
foreach (Property p in ps)
{
Console.WriteLine(p.Type.ToString() + ">" + p.SubType.ToString() + ">"
+ p.PropertyID + " > " + p.Name + " > " + p.get_Value());
}
}
private static void AdjustScannerSettings(IItem scannnerItem, int scanResolutionDPI, int scanStartLeftPixel,
int scanStartTopPixel, int scanWidthPixels, int scanHeightPixels,
int brightnessPercents, int contrastPercents, int colorMode)
{
IProperties ps = scannnerItem.Properties;
//showPropValues(ps);
SetWIAProperty(ps, WiaPropertyConstant.HorizontalResolution, scanResolutionDPI);
SetWIAProperty(ps, WiaPropertyConstant.VerticalResolution, scanResolutionDPI);
//(最大-页宽)/2
object propNameStr = "" + WiaPropertyConstant.HorizontalExtent;
Property hExt = ps.get_Item(ref propNameStr);
scanStartLeftPixel = (int)Decimal.Round(((int)hExt.get_Value() - scanWidthPixels) / 2);
SetWIAProperty(ps, WiaPropertyConstant.HorizontalStartPostion, scanStartLeftPixel);
SetWIAProperty(ps, WiaPropertyConstant.VerticalStartPosition, scanStartTopPixel);
SetWIAProperty(ps, WiaPropertyConstant.HorizontalExtent, scanWidthPixels);
SetWIAProperty(ps, WiaPropertyConstant.VerticalExtent, scanHeightPixels);
SetWIAProperty(ps, WiaPropertyConstant.Brightness, brightnessPercents);
SetWIAProperty(ps, WiaPropertyConstant.Contrast, contrastPercents);
SetWIAProperty(ps, WiaPropertyConstant.BitsPerPixel, 1); //默认24,8,1
//SetWIAProperty(ps, WiaPropertyConstant.DocumentHandlingSelect, 5);
//SetWIAProperty(ps, WiaPropertyConstant.Pages, 2);
SetWIAProperty(ps, WiaPropertyConstant.CurrentIntent, colorMode);
//showPropValues(ps);
}
private static void SetWIAProperty(IProperties properties, int propName, object propValue)
{
try
{
object propNameStr = "" + propName;
Property prop = properties.get_Item(ref propNameStr);
if (prop != null)
{
//Console.WriteLine(prop.get_Value().ToString());
prop.set_Value(ref propValue);
}
else
{
Console.WriteLine("prop null" + propNameStr);
}
}
catch (Exception e)
{
Console.WriteLine(propName + " > " + e);
}
}
public override string ToString()
{
if (deviceName != null && deviceName.Length > 0)
{
return deviceName;
}
if (this._deviceInfo != null)
{
return (string)this._deviceInfo.Properties["Name"].get_Value();
}
return "Null";
}
}
}