Как сохранить TWAIN отсканированное изображение в JPEG файл?
В этом разделе
Вы можете получить изображение от TWAIN сканера и сохранить его как файл JPEG тремя способами:
1. С помощью JPEG кодека из SDK для режимов передачи Native или Memory
- Этот метод работает для любого TWAIN сканера.
- Изображение кодируется с помощью внутреннего кодека SDK.
- Качество JPEG можно установить с помощью свойства Vintasoft.Twain.ImageEncoders.TwainJpegEncoderSettings.JpegQuality.
-
Изображение сохраняется в файл JPEG с помощью метода Vintasoft.Twain.AcquiredImage.Save.
-
Вот C#/VB.NET код, который демонстрирует, как отсканировать изображение и сохранить его как JPEG файл, используя JPEG кодек SDK:
/// <summary>
/// Synchronously acquires not compressed images from TWAIN device and saves images to JPEG files.
/// </summary>
static void AcquireNotCompressedImagesFromTwainDeviceAndSaveImagesToJpegFiles()
{
// create the device manager
using (Vintasoft.Twain.DeviceManager deviceManager = new Vintasoft.Twain.DeviceManager())
{
// open the device manager
deviceManager.Open();
// get reference to the default device
Vintasoft.Twain.Device device = deviceManager.DefaultDevice;
// specify that device UI must not be used
device.ShowUI = false;
// open the device
device.Open();
// specify that Memory transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.Memory;
// acquire images from device
Vintasoft.Twain.AcquireModalState acquireModalState = Vintasoft.Twain.AcquireModalState.None;
do
{
acquireModalState = device.AcquireModal();
switch (acquireModalState)
{
case Vintasoft.Twain.AcquireModalState.ImageAcquired:
// specify JPEG encoder settings
Vintasoft.Twain.ImageEncoders.TwainJpegEncoderSettings jpegEncoderSettings =
new Vintasoft.Twain.ImageEncoders.TwainJpegEncoderSettings();
jpegEncoderSettings.JpegQuality = 50;
// save acquired image to a disk, internal SDK encoder will be used
device.AcquiredImage.Save("test.jpg", jpegEncoderSettings);
// dispose acquired image
device.AcquiredImage.Dispose();
break;
}
}
while (acquireModalState != Vintasoft.Twain.AcquireModalState.None);
// close the device
device.Close();
// close the device manager
deviceManager.Close();
}
}
''' <summary>
''' Synchronously acquires not compressed images from TWAIN device and saves images to JPEG files.
''' </summary>
Private Shared Sub AcquireNotCompressedImagesFromTwainDeviceAndSaveImagesToJpegFiles()
' create the device manager
Using deviceManager As New Vintasoft.Twain.DeviceManager()
' open the device manager
deviceManager.Open()
' get reference to the default device
Dim device As Vintasoft.Twain.Device = deviceManager.DefaultDevice
' specify that device UI must not be used
device.ShowUI = False
' open the device
device.Open()
' specify that Memory transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.Memory
' acquire images from device
Dim acquireModalState As Vintasoft.Twain.AcquireModalState = Vintasoft.Twain.AcquireModalState.None
Do
acquireModalState = device.AcquireModal()
Select Case acquireModalState
Case Vintasoft.Twain.AcquireModalState.ImageAcquired
' specify JPEG encoder settings
Dim jpegEncoderSettings As New Vintasoft.Twain.ImageEncoders.TwainJpegEncoderSettings()
jpegEncoderSettings.JpegQuality = 50
' save acquired image to a disk, internal SDK encoder will be used
device.AcquiredImage.Save("test.jpg", jpegEncoderSettings)
' dispose acquired image
device.AcquiredImage.Dispose()
Exit Select
End Select
Loop While acquireModalState <> Vintasoft.Twain.AcquireModalState.None
' close the device
device.Close()
' close the device manager
deviceManager.Close()
End Using
End Sub
2. С помощью JPEG кодека TWAIN драйвера для режима передачи File
- Драйвер TWAIN должен иметь встроенный кодек JPEG - вы можете проверить это с помощью метода Vintasoft.Twain.Device.GetSupportedImageFileFormats.
- Драйвер TWAIN кодирует полученное изображение и сохраняет его непосредственно в файл на диске.
- Сжатие JPEG можно установить с помощью свойства Vintasoft.Twain.Device.FileFormat.
- Имя файла JPEG можно задать с помощью свойства Vintasoft.Twain.Device.FileName.
-
Качество файла JPEG можно установить с помощью свойства Vintasoft.Twain.Device.FileJpegQuality.
-
Вот C#/VB.NET код, который демонстрирует, как сохранить отсканированное изображение непосредственно на диск в виде файла JPEG:
/// <summary>
/// Starts synchronous acquisition of image from TWAIN device and specifies that acquired JPEG compressed images must be saved directly to JPEG files on disk.
/// </summary>
static void StartSynchronousTwainScanningAndSpecifyThatJpegCompressedImagesMustBeSavedDirectlyToJpegFiles()
{
// create the device manager
using (Vintasoft.Twain.DeviceManager deviceManager = new Vintasoft.Twain.DeviceManager())
{
// open the device manager
deviceManager.Open();
// get reference to the default device
Vintasoft.Twain.Device device = deviceManager.DefaultDevice;
// specify that device UI must not be used
device.ShowUI = false;
// open the device
device.Open();
// check if device driver can save image to disk as JPEG files
Vintasoft.Twain.TwainImageFileFormat[] supportedImageFileFormats = device.GetSupportedImageFileFormats();
bool isJpegFileFormatSupported = false;
for (int i = 0; i < supportedImageFileFormats.Length; i++)
{
if (supportedImageFileFormats[i] == Vintasoft.Twain.TwainImageFileFormat.Jpeg)
{
isJpegFileFormatSupported = true;
break;
}
}
//
if (!isJpegFileFormatSupported)
{
// close the device
device.Close();
// close the device manager
deviceManager.Close();
//
return;
}
// specify that File transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.File;
// save images as JPEG files
device.FileFormat = Vintasoft.Twain.TwainImageFileFormat.Jpeg;
// set JPEG quality
device.FileJpegQuality = 50;
int acquiredImageCount = 0;
// acquire images from device
Vintasoft.Twain.AcquireModalState acquireModalState;
do
{
acquireModalState = device.AcquireModal();
switch (acquireModalState)
{
case Vintasoft.Twain.AcquireModalState.ImageAcquiring:
// set the filename for image
device.FileName = string.Format("test{0}.jpg", acquiredImageCount);
break;
case Vintasoft.Twain.AcquireModalState.ImageAcquired:
// image is already saved to disk as JPEG file
// specify name for next acquired image
acquiredImageCount++;
break;
}
}
while (acquireModalState != Vintasoft.Twain.AcquireModalState.None);
// close the device
device.Close();
// close the device manager
deviceManager.Close();
}
}
''' <summary>
''' Starts synchronous acquisition of image from TWAIN device and specifies that acquired JPEG compressed images must be saved directly to JPEG files on disk.
''' </summary>
Private Shared Sub StartSynchronousTwainScanningAndSpecifyThatJpegCompressedImagesMustBeSavedDirectlyToJpegFiles()
' create the device manager
Using deviceManager As New Vintasoft.Twain.DeviceManager()
' open the device manager
deviceManager.Open()
' get reference to the default device
Dim device As Vintasoft.Twain.Device = deviceManager.DefaultDevice
' specify that device UI must not be used
device.ShowUI = False
' open the device
device.Open()
' check if device driver can save image to disk as JPEG files
Dim supportedImageFileFormats As Vintasoft.Twain.TwainImageFileFormat() = device.GetSupportedImageFileFormats()
Dim isJpegFileFormatSupported As Boolean = False
For i As Integer = 0 To supportedImageFileFormats.Length - 1
If supportedImageFileFormats(i) = Vintasoft.Twain.TwainImageFileFormat.Jpeg Then
isJpegFileFormatSupported = True
Exit For
End If
Next
'
If Not isJpegFileFormatSupported Then
' close the device
device.Close()
' close the device manager
deviceManager.Close()
'
Return
End If
' specify that File transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.File
' save images as JPEG files
device.FileFormat = Vintasoft.Twain.TwainImageFileFormat.Jpeg
' set JPEG quality
device.FileJpegQuality = 50
Dim acquiredImageCount As Integer = 0
' acquire images from device
Dim acquireModalState As Vintasoft.Twain.AcquireModalState
Do
acquireModalState = device.AcquireModal()
Select Case acquireModalState
Case Vintasoft.Twain.AcquireModalState.ImageAcquiring
' set the filename for image
device.FileName = String.Format("test{0}.jpg", acquiredImageCount)
Exit Select
Case Vintasoft.Twain.AcquireModalState.ImageAcquired
' image is already saved to disk as JPEG file
' specify name for next acquired image
acquiredImageCount += 1
Exit Select
End Select
Loop While acquireModalState <> Vintasoft.Twain.AcquireModalState.None
' close the device
device.Close()
' close the device manager
deviceManager.Close()
End Using
End Sub
3. С помощью JPEG кодека TWAIN драйвера для режима передачи Memory
- Драйвер TWAIN должен иметь встроенный кодек JPEG - вы можете проверить это с помощью метода Vintasoft.Twain.Device.GetSupportedImageCompressions.
- Драйвер TWAIN возвращает полученное изображение в виде потока JPEG.
- Сжатие JPEG можно установить с помощью свойства Vintasoft.Twain.Device.ImageCompression.
-
Качество файла JPEG можно установить с помощью характеристики Vintasoft.Twain.DeviceCapabilityId.IJpegQuality.
-
Вот C#/VB.NET код, который демонстрирует, как отсканировать изображение в виде потока JPEG и сохранить его в файл на диске:
/// <summary>
/// Synchronously acquires JPEG compressed images from TWAIN device and saves images to JPEG files.
/// </summary>
static void AcquireJpegCompressedImagesFromTwainDeviceAndSaveImagesToJpegFiles()
{
// create the device manager
using (Vintasoft.Twain.DeviceManager deviceManager = new Vintasoft.Twain.DeviceManager())
{
// open the device manager
deviceManager.Open();
// get reference to the default device
Vintasoft.Twain.Device device = deviceManager.DefaultDevice;
// specify that device UI must not be used
device.ShowUI = false;
// open the device
device.Open();
// check if device driver can return image data as JPEG stream
Vintasoft.Twain.TwainImageCompression[] supportedImageCompressions = device.GetSupportedImageCompressions();
bool isJpegCompressionSupported = false;
for (int i = 0; i < supportedImageCompressions.Length; i++)
{
if (supportedImageCompressions[i] == Vintasoft.Twain.TwainImageCompression.Jpeg)
{
isJpegCompressionSupported = true;
break;
}
}
//
if (!isJpegCompressionSupported)
{
// close the device
device.Close();
// close the device manager
deviceManager.Close();
//
return;
}
// specify that Memory transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.Memory;
// set JPEG compression for image data
device.ImageCompression = Vintasoft.Twain.TwainImageCompression.Jpeg;
// set JPEG quality
Vintasoft.Twain.DeviceCapability jpegQualityCap = device.Capabilities.Find(Vintasoft.Twain.DeviceCapabilityId.IJpegQuality);
if (jpegQualityCap != null)
jpegQualityCap.SetValue((int)50);
// acquire images from device
Vintasoft.Twain.AcquireModalState acquireModalState;
do
{
acquireModalState = device.AcquireModal();
switch (acquireModalState)
{
case Vintasoft.Twain.AcquireModalState.ImageAcquired:
// save acquired image to disk, SDK will save JPEG stream received from device driver
device.AcquiredImage.Save("test.jpg");
// dispose the acquired image
device.AcquiredImage.Dispose();
break;
}
}
while (acquireModalState != Vintasoft.Twain.AcquireModalState.None);
// close the device
device.Close();
// close the device manager
deviceManager.Close();
}
}
''' <summary>
''' Synchronously acquires JPEG compressed images from TWAIN device and saves images to JPEG files.
''' </summary>
Private Shared Sub AcquireJpegCompressedImagesFromTwainDeviceAndSaveImagesToJpegFiles()
' create the device manager
Using deviceManager As New Vintasoft.Twain.DeviceManager()
' open the device manager
deviceManager.Open()
' get reference to the default device
Dim device As Vintasoft.Twain.Device = deviceManager.DefaultDevice
' specify that device UI must not be used
device.ShowUI = False
' open the device
device.Open()
' check if device driver can return image data as JPEG stream
Dim supportedImageCompressions As Vintasoft.Twain.TwainImageCompression() = device.GetSupportedImageCompressions()
Dim isJpegCompressionSupported As Boolean = False
For i As Integer = 0 To supportedImageCompressions.Length - 1
If supportedImageCompressions(i) = Vintasoft.Twain.TwainImageCompression.Jpeg Then
isJpegCompressionSupported = True
Exit For
End If
Next
'
If Not isJpegCompressionSupported Then
' close the device
device.Close()
' close the device manager
deviceManager.Close()
'
Return
End If
' specify that Memory transfer mode must be used
device.TransferMode = Vintasoft.Twain.TransferMode.Memory
' set JPEG compression for image data
device.ImageCompression = Vintasoft.Twain.TwainImageCompression.Jpeg
' set JPEG quality
Dim jpegQualityCap As Vintasoft.Twain.DeviceCapability = device.Capabilities.Find(Vintasoft.Twain.DeviceCapabilityId.IJpegQuality)
If jpegQualityCap IsNot Nothing Then
jpegQualityCap.SetValue(CInt(50))
End If
' acquire images from device
Dim acquireModalState As Vintasoft.Twain.AcquireModalState
Do
acquireModalState = device.AcquireModal()
Select Case acquireModalState
Case Vintasoft.Twain.AcquireModalState.ImageAcquired
' save acquired image to disk, SDK will save JPEG stream received from device driver
device.AcquiredImage.Save("test.jpg")
' dispose the acquired image
device.AcquiredImage.Dispose()
Exit Select
End Select
Loop While acquireModalState <> Vintasoft.Twain.AcquireModalState.None
' close the device
device.Close()
' close the device manager
deviceManager.Close()
End Using
End Sub