using System;
|
using System.Collections.Generic;
|
using System.Drawing;
|
using System.Drawing.Imaging;
|
using System.Runtime.InteropServices;
|
using System.Windows;
|
using System.Windows.Media;
|
using System.Windows.Media.Imaging;
|
|
namespace Bro.Common.ImageCanvas
|
{
|
public static class StaticHelper
|
{
|
static BitmapPalette palette8Index = null;
|
static BitmapPalette Palette8Index
|
{
|
get
|
{
|
if (palette8Index == null)
|
{
|
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
|
for (int i = 0; i < 256; i++)
|
{
|
colors.Add(System.Windows.Media.Color.FromRgb((byte)i, (byte)i, (byte)i));
|
}
|
palette8Index = new BitmapPalette(colors);
|
}
|
|
return palette8Index;
|
}
|
}
|
|
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
|
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
|
|
public static WriteableBitmap BitmapToWriteableBitmap(this Bitmap image)
|
{
|
BitmapPalette palette = null;
|
System.Windows.Media.PixelFormat format = PixelFormats.Bgr32;
|
switch (image.PixelFormat)
|
{
|
case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
|
format = PixelFormats.Bgr32;
|
break;
|
case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
|
format = PixelFormats.Bgr24;
|
break;
|
case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
|
format = PixelFormats.Indexed8;
|
//List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
|
//for (int i = 0; i < 256; i++)
|
//{
|
// colors.Add(System.Windows.Media.Color.FromRgb((byte)i, (byte)i, (byte)i));
|
//}
|
//palette = new BitmapPalette(colors);
|
palette = Palette8Index;
|
break;
|
}
|
|
WriteableBitmap wbmp = new WriteableBitmap(image.Width, image.Height, 96, 96, format, palette);
|
|
var bytes = (uint)wbmp.PixelWidth * (uint)wbmp.PixelHeight * (uint)wbmp.Format.BitsPerPixel / (uint)8;
|
|
var rBitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
|
ImageLockMode.ReadOnly, image.PixelFormat);
|
|
wbmp.Lock();
|
unsafe
|
{
|
//Buffer.MemoryCopy(rBitmapData.Scan0.ToPointer(), wbmp.BackBuffer.ToPointer(), bytes, bytes);
|
CopyMemory(wbmp.BackBuffer, rBitmapData.Scan0, bytes);
|
//byte[] rawData = new byte[bytes];
|
//Marshal.Copy(rBitmapData.Scan0, rawData, 0, bytes);
|
//Marshal.Copy(rawData, 0, wbmp.BackBuffer, rawData.Length);
|
}
|
wbmp.AddDirtyRect(new Int32Rect(0, 0, image.Width, image.Height));
|
wbmp.Unlock();
|
|
image.UnlockBits(rBitmapData);
|
|
return wbmp;
|
}
|
|
[DllImport("gdi32.dll")]
|
static extern bool DeleteObject(IntPtr hObject);
|
public static ImageSource BitmapToImageSource(this Bitmap image)
|
{
|
IntPtr myImagePtr = image.GetHbitmap(); //创建GDI对象,返回指针
|
|
BitmapSource imgsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(myImagePtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //创建imgSource
|
|
DeleteObject(myImagePtr);
|
|
return imgsource;
|
}
|
}
|
}
|