using System.IO;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Media;
using System.Drawing;
using System.Drawing.Imaging;
namespace ImageUtils
{
public static class Converter
{
///
/// 将 Bitmap 转化为 BitmapSource
///
/// 要转换的 Bitmap
/// 转换后的 BitmapSource
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bmp)
{
System.IntPtr hBitmap = bmp.GetHbitmap();
try
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, System.IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(hBitmap);
}
}
///
/// 将 BitmapSource 转化为 Bitmap
///
/// 要转换的 BitmapSource
/// 转化后的 Bitmap
public static System.Drawing.Bitmap ToBitmap(this BitmapSource source)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
encoder.Save(ms);
return new System.Drawing.Bitmap(ms);
}
}
public static System.Array TifToArray(string tifPath)
{
//string tifPath = "test.tif";
// 方式1:
//Stream imageStreamSource = new FileStream(tifPath, FileMode.Open, FileAccess.Read, FileShare.Read);
//TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
//BitmapSource bitmapSource = decoder.Frames[0];
//Bitmap bitmap = ToBitmap(bitmapSource);
//方式2:更简洁的方式: tif -> bitmap
Image tifImage = Image.FromFile(tifPath);
Bitmap bitmap = new Bitmap(tifImage);
//...
}
}