BMP dallo scanner – Codice VB.NET

BMP dallo scanner in VB.NET: ovvero come settare lo scanner e creare una bmp in memoria usabile in qualsiasi punto del vostro listato.

Lo scanner è ormai un dispositivo presente in tutte le postazioni di pc domestici e professionali: scansionare foto, documenti, fare fotocopie è qualcosa ormai all’ordine del giorno. Come fare ricavare una bmp dallo scanner? Ci viene in aiuto la funzione IngAC_SCAN_TO_MEM(DPI As Integer, Prof_Colore As Byte, Dim_X_mm As Integer, Dim_Y_mm As Integer, Pos_X_mm As Integer, Pos_Y_mm As Integer, Luminosita As Integer, Contrasto As Integer) As Bitmap. Grazie ad essa saremo in grado di ricavare una bmp dallo scanner con pochi passaggi.

[codesyntax lang=”vbnet”]

Public Function IngAC_SCAN_TO_MEM(DPI As Integer,
                                      Prof_Colore As Byte,
                                      Dim_X_mm As Integer,
                                      Dim_Y_mm As Integer,
                                      Pos_X_mm As Integer,
                                      Pos_Y_mm As Integer,
                                      Luminosita As Integer,
                                      Contrasto As Integer
                                      ) As Bitmap
        IngAC_SCAN_TO_MEM = Nothing
        Dim Seleziona_Dispositivo As WIA.Device = Nothing
        Dim Dispositivo_Scanner As WIA.Device = Nothing
        Dim Finestra As New WIA.CommonDialog
        Try
            Dispositivo_Scanner = Finestra.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, False, False)
            If Not Dispositivo_Scanner Is Nothing Then
                Seleziona_Dispositivo = Dispositivo_Scanner
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Avviso!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
        'profondità di colore: 4 Black-white, Grayscale 2, Color 1
        'si imposta il rapporto dpix/dpiy=1
        Dim DPI_X = DPI
        Dim DPI_Y = DPI
        ' dimensioni dell'area
        Dim Dim_X_inch As Double
        Dim Dim_Y_inch As Double
        ' offset posizione x,y dell'origine
        Dim Pos_X_inch As Double
        Dim Pos_Y_inch As Double
        ' conversioni da inch a mm
        Dim_X_inch = Int(10 * Dim_X_mm / 25.4) / 10
        Dim_Y_inch = Int(10 * Dim_Y_mm / 25.4) / 10
        Pos_X_inch = Pos_X_mm / 25.4
        Pos_Y_inch = Pos_Y_mm / 25.4
        ' scansione su file
        If Not Dispositivo_Scanner Is Nothing Then
            For Each Itm In Dispositivo_Scanner.Items
                For Each ItmProp In Itm.Properties
                    ' gestisce le proprietà dello scanner
                    Select Case ItmProp.PropertyID
                        '======================================
                        Case 6147 ' Risoluzione orizzontale
                            Try
                                ItmProp.Value = DPI_X
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "DPI_X Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6148 ' Risoluzione verticale
                            Try
                                ItmProp.Value = DPI_Y
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "DPI_Y Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6151   ' Scanning Area X
                            Try
                                ItmProp.Value = Dim_X_inch * DPI_X
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "DIM_X Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6152 ' Scanning Area Y
                            Try
                                ItmProp.Value = Dim_Y_inch * DPI_Y
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "DIM_Y Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6149 ' Posizione inizio scansione X
                            Try
                                ItmProp.Value = Pos_X_inch * DPI_X
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "POS_X Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6150 ' Posizione inizio scansione Y
                            Try
                                ItmProp.Value = Pos_Y_inch * DPI_Y
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "POS_Y Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6146 ' Profondita di colore
                            Try
                                ItmProp.Value = Prof_Colore
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "Prof_Colore Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6154 ' Luminosità
                            Try
                                ItmProp.Value = Luminosita
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "Lumin(-100;+100)", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                        '======================================
                        Case 6155 ' Contrasto
                            Try
                                ItmProp.Value = Contrasto
                            Catch ex As Exception
                                MessageBox.Show(ex.Message, "Contr(-100;+100)", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                                Return Nothing
                            End Try
                    End Select
                Next
            Next
            ' prende il device disponibile
            Dim Item As WIA.Item = Dispositivo_Scanner.Items(1)
            Dim ImageFile As WIA.ImageFile
            Try
                ImageFile = Finestra.ShowTransfer(Item, , True)
                Dim MStream As IO.MemoryStream = Nothing
                Try
                    'Convert l' output raw dello scanner in un byte array
                    Dim ImgBytes() As Byte = DirectCast(ImageFile.FileData.BinaryData, Byte())
                    'Legge i byte dell'immagine 
                    MStream = New MemoryStream(ImgBytes)
                    'Crea una Bitmap dallo stream
                    Dim Bmp As New Bitmap(MStream)
                    'la funzione restituisce la Bitmap
                    IngAC_SCAN_TO_MEM = Bmp
                Catch ex As Exception
                    MsgBox("Errore durante la conversione a bitmap: " & ex.Message)
                End Try
                If MStream IsNot Nothing Then MStream.Dispose()
            Catch ex As Exception
                MessageBox.Show("Error in IngAC_SCAN_TO_MEM: ", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Function

[/codesyntax]

Come ricavare una BMP dallo scanner

La funzione IngAC_SCAN_TO_MEM ha come input:

  • DPI che rappresenta i dpi (attenzione a usare un valore supportato dal vostro scanner: un valore standard è 300).
  • Prof_Colore che rappresenta la profondità di colore: 1 full color; 2 grayscale; 4 black & white.
  • Dim_X_mm è la dimensione orizzontale dell’area in millimetri che si vuole scansionare (se fosse un formato A4 sarebbe 210).
  • Dim_Y_mm è la dimensione verticale dell’area in millimetri che si vuole scansionare (se fosse un formato A4 sarebbe 297).
  • Pos_X_mm è la posizione orizzontale (offset) in millimetri da cui si vuole iniziare a scansionare (ad esempio potremmo voler scansionare solo un quadratino 50x50mm al centro del foglio A4).
  • Pos_Y_mm  è la posizione verticale (offset) in millimetri da cui si vuole iniziare a scansionare (ad esempio potremmo voler scansionare solo un quadratino 50x50mm al centro del foglio A4).
  • Luminosita: il valore standard è zero e varia tra – 100 e + 100.
  • Contrasto: il valore standard è zero e varia tra – 100 e + 100.

In output avremo una mappa di byte (BMP) salvata in memoria, da passare direttamente a una PictureBox o elaborarla come più ci aggrada.

Funzionamento di IngAC_SCAN_TO_MEM()

Il funzionamento è abbastanza lineare; occorre innanzi tutto includere nei riferimenti la Windows Image Acquisition (WIA)  che permette di accedere allo scanner ed è presente in quasi tutti i sistemi Windows. Ottenere una BMP dallo scanner sarà immediato e semplicissimo.

Dal menu “Progetto” cliccare su “Aggiungi riferimento…”, quindi

Scanner_to_BMP

selezionare COM -> librerie dei tipi e cercare Microsoft Windows Image Acquisition Library e spuntare.

Aggiungere WIA nei riferimenti VB.Net

A questo punto basta copiare il listato che è commentato opportunamente. In caso di errori apparirà un MsgBox con una piccola spiegazione.

Nota: ricordarsi di Imports System.IO in testa al listato, per poter usare la funzione.

Link Utili:

BMP dallo scanner - Codice VB.NET

BMP dallo scanner – Codice VB.NET

You may also like...