c++ – Getting an image from a scanner in C ++


you need to get an image from a scanner (I write in C ++, the program after receiving it saves it in the database, etc.). Having searched a little on the Internet, I realized that I needed to use COM objects, as well as WIA (Windows Image Acquisition), but I did not have a clear understanding of how to implement all this, since C # was used almost everywhere for this task.

Could you tell me how to implement this?


Because there are still no answers, there is a proposal … not better, but still .. as an alternative.

I have some vbsript code lying around somewhere on the Internet, it can be 1. Encapsulated via ActiveX ScriptControl . 2. Translate into с++ .

wiaaut.dll for work and use it.

There was a scanner, it was necessary to automate scanning by pressing a button on the scanner (the wiaacmgr scan wizard program was launched, I replaced it with this one). When the scanner is working, a window "scanning in progress" hangs in the background.

Also, by poking a little with this code, you can get pictures from the camera)

Option Explicit

On Error Resume Next
dim fs
set fs = CreateObject("Scripting.FileSystemObject")
dim wsh
set wsh = CreateObject("WScript.Shell")
dim apath
apath = "D:\scaner"

a = wsh.ExpandEnvironmentStrings("%System%Root%")
if len(a) > 0 then
  if not fs.FileExists(a & "\wiaaut.dll") then
   fs.CopyFile apath & "\wiaaut.dll",a & "\wiaaut.dll",true
   wsh.Run("regsvr32.exe "&a & "\wiaaut.dll")
  end if
end if

'//WScript.Echo fs

if fs.FileExists(apath &"\tempcheck1.tmp")  then  
  a = wsh.popup("Сканирование уже запущено, запуcтить повторно?",3, "Защита от повторного запуска", 3 + 48 )
  if a<>6 then 
    WScript.Quit(0)                       ' Защита от повторного запуска
  end if
end if

set tmpfile = fs.CreateTextFile(apath &"\tempcheck1.tmp")

dim f2, counter1

if fs.FileExists(apath &"\counter.tmp") then
   set f2 = fs.OpenTextFile(apath &"\counter.tmp")
   set f2=fs.OpenTextFile(apath &"\counter.tmp",2)
  set f2=fs.CreateTextFile(apath &"\counter.tmp")
  counter1 = 1
end if

counter1 = "scan" & Right("0000"&counter1 , 4) & ".jpg"

'msgbox 1

'WScript.Echo 1

Const ScannerDeviceType = 1
Const ColorIntent = 1
Const wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"

Dim objDeviceManager
Dim objDeviceInfos
Dim objDevice

Dim objImageFile
Dim objImageProcess

Dim strPath2Save
Dim strFormat
Dim intQuality
Dim intDPI
Dim intHorizontalSize
Dim intVerticalSize

' Задаём характеристики изображения
'msgbox counter1
strPath2Save      = "c:\MyImage.jpg"      ' Полное имя файла для сохранения
strPath2Save      = "d:\Full_Access\scan\" & counter1
'msgbox strPath2Save

strFormat         = wiaFormatJPEG         ' Формат файла - *.jpg
intQuality        = 85                    ' Качество jpg
intDPI            = 300                   ' Разрешение - 150 dpi
intHorizontalSize = (210 / 25.4) * intDPI ' Размер по горизонтали - A4
intVerticalSize   = (297 / 25.4) * intDPI ' Размер по вертикали - A4

Set objDeviceManager = WScript.CreateObject("WIA.DeviceManager")
Set objDeviceInfos = objDeviceManager.DeviceInfos

If objDeviceInfos.Count > 0 Then
    ' Выбираем устройство для сканирования. Если оно единственное, то сие произойдёт без отображения диалога.
     Set objDevice = WScript.CreateObject("WIA.CommonDialog").ShowSelectDevice(ScannerDeviceType, False, False)
    ' Кроме того, зная DeviceID устройства, можно использовать иной способ подключения, например:
    'Dim objDeviceInfo
    'For Each objDeviceInfo In objDeviceManager.DeviceInfos
    '    WScript.Echo objDeviceInfo.DeviceID
    '    If objDeviceInfo.DeviceID = "{6BDD1FC6-810F-11D0-BEC7-08002BE2092F}\0000" Then
    '        Set objDevice = objDeviceInfo.Connect
    '    End If

    If Not objDevice Is Nothing Then
        '//WScript.Echo objDevice.Properties.Item("Name") & " [" & objDevice.DeviceID & "]"
        'WScript.Echo "Scanning..."

        With objDevice
            With .Items(1)
                ' Задаём требуемые характеристики изображения для сканирования
                With .Properties
                    .Item("6146").Value = ColorIntent             ' Цветовая модель (Current Intent)

                    ' Разрешение:
                    .Item("6147").Value = intDPI                  ' :по горизонтали (Horizontal Resolution)
                    .Item("6148").Value = intDPI                  ' :по вертикали (Vertical Resolution)

                    ' Начало области сканирования:
                    .Item("6149").Value = 0                       ' :по горизонтали (Horizontal Start Position)
                    .Item("6150").Value = 0                       ' :по вертикали (Vertical Start Position)

                    ' Размер области сканирования:
                    .Item("6151").Value = intHorizontalSize       ' :по горизонтали (Horizontal Extent)
                    .Item("6152").Value = intVerticalSize         ' :по вертикали (Vertical Extent)
                End With

                ' Инициируем начало операции сканирования
                Set objImageFile = .Transfer()

                ' Конвертируем полученное изображение
                'WScript.Echo "Converting..."

                Set objImageProcess = WScript.CreateObject("WIA.ImageProcess")

                With objImageProcess
                    With .Filters
                        .Add objImageProcess.FilterInfos("Convert").FilterID

                        With .Item(1).Properties
                            .Item("FormatID").Value = strFormat  ' Формат изображения
                            .Item("Quality").Value  = intQuality ' Качество изображения
                        End With
                    End With

                    Set objImageFile = .Apply(objImageFile)
                End With
            End With
        End With

        ' Если файл существует - предварительно удаляем его
        With WScript.CreateObject("Scripting.FileSystemObject")
            If .FileExists(strPath2Save) Then
                .DeleteFile strPath2Save
            End If
        End With

        ' Сохраняем полученное изображение
        objImageFile.SaveFile strPath2Save

        'WScript.Echo "Complete."

        Set objDevice = Nothing
       ' WScript.Echo "Cancel scanning by user"
    End If
    WScript.Echo "No connected devices"
End If

Set objDeviceManager = Nothing
Set objDeviceInfos   = Nothing


set f2 = fs.GetFile(strPath2Save)
d2 = split(f2.DateCreated & " "," ")(0)

WScript.Quit 0

'REGEDIT4         {D13E3F25-1688-45A0-9743-759EB35CDF9A}


Similar question http://stackoverflow.com/questions/8812342/scanning-pages-using-wia-or-twain

Scroll to Top