要将 IPictureDisp 转换为 System.Drawing.Image,您需要使用 OLE 自动化和 Windows 窗体的图像处理功能。以下是一个简单的示例,说明如何执行此操作:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public static Image ConvertIPictureDispToImage(object picture)
{
if (picture == null)
throw new ArgumentNullException("picture");
// 获取图片的句柄
IntPtr hPal = GetStockObject(DEFAULT_PALETTE);
IntPtr hdc = GetDC(IntPtr.Zero);
IntPtr hdcMem = CreateCompatibleDC(hdc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr hOldPal = IntPtr.Zero;
Image img = null;
try
{
// 获取图片的宽度和高度
int width = picture.Width;
int height = picture.Height;
// 创建兼容的位图
hBitmap = CreateCompatibleBitmap(hdc, width, height);
// 选择新的位图
hOldPal = SelectPalette(hdcMem, hPal, 0);
RealizePalette(hdcMem);
SelectObject(hdcMem, hBitmap);
// 绘制图片
picture.Render(hdcMem, 0, 0, width, height, 0, height, width, -height, IntPtr.Zero);
// 将位图转换为 System.Drawing.Image
Bitmap bmp = Image.FromHbitmap(hBitmap);
img = (Image)bmp.Clone();
}
finally
{
// 释放资源
if (hOldPal != IntPtr.Zero)
SelectPalette(hdcMem, hOldPal, 0);
if (hBitmap != IntPtr.Zero)
DeleteObject(hBitmap);
if (hdcMem != IntPtr.Zero)
DeleteDC(hdcMem);
if (hdc != IntPtr.Zero)
ReleaseDC(IntPtr.Zero, hdc);
}
return img;
}
这个方法将 IPictureDisp 转换为 System.Drawing.Image,并且不涉及任何云计算品牌商。
领取专属 10元无门槛券
手把手带您无忧上云