您当前的位置: 首页 >  c#

惊鸿一博

暂无认证

  • 5浏览

    0关注

    535博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

TIF图片转bitmap的两种方式(C#)

惊鸿一博 发布时间:2020-08-22 22:53:04 ,浏览量:5

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);

            //...
    }
}

 

关注
打赏
1663399408
查看更多评论
立即登录/注册

微信扫码登录

0.0926s