C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using WIA;
namespace MyLib1
{
public class MySharpClass1
{
const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
public static string convertBitmapToBase64(BitmapImage bi)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bi));
encoder.Save(ms);
byte[] bitmapdata = ms.ToArray();
return Convert.ToBase64String(bitmapdata);
}
public static string convBmpToBase64Strings(Bitmap bmp, ImageFormat imageFormat)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
void SharpScanDocument()
{
DeviceManager deviceManager;
DeviceInfos devices;
deviceManager = new DeviceManager();
devices = deviceManager.DeviceInfos;
DeviceInfo selectedDevice;
Device ourdevice;
int selectedScanIndex = 0;
string base64String = "";
for (int i = 1; i <= devices.Count; i++)
{
DeviceInfo device;
device = devices[i];
if (device.Type == WiaDeviceType.ScannerDeviceType)
{
selectedScanIndex = i;
}
}
if (selectedScanIndex > 0)
{
selectedDevice = devices[selectedScanIndex];
ourdevice = selectedDevice.Connect();
Items items;
items = ourdevice.Items;
WIA.Item item = ourdevice.Items[1] as WIA.Item;
WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
WIA.ImageFile img = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);
byte[] buffer = (byte[])img.FileData.get_BinaryData();
MemoryStream ms = new MemoryStream(buffer);
Bitmap bmp = new Bitmap(Image.FromStream(ms));
base64String = convBmpToBase64Strings(bmp, bmp.RawFormat);
}
Console.WriteLine($"Scan done");
Console.ReadLine();
}
}
}
C++
include "pch.h"
include "CppLib1.h"
namespace MyCppSpace {
class CppLib1 {
void testSharpCall() {
MyLib1::MySharpClass1::SharpScanDocument();
}
};
}