C# 图片操作(图片读取,保存,转换,传输)

 JPG PNG GIF BMP图片格式的区别:

类型 优点 缺点 应用场景 相同图片大小比较
BMP 无损压缩,图质最好 文件太大,不利于网络传输 152K
GIF 动画存储格式 最多256色,画质差 53K
PNG 可保存透明背景的图片 画质中等 202K
JPG 文件小,利于网络传输 画质损失 车牌识别 84K

 图片代码操作:

 根据图片的相对路径 获取Image对象:

      /// 
        /// 根据图片的相对路径 获取Image对象
        /// 
        /// 图片的相对路径(如:@"/images/star.png")
        /// 
        public static Image GetImage(string imgPath)
        {
            if (File.Exists(imgPath))
            {
                Image im = new Image();
                im.Source = GetBitmapImage(imgPath);
                return im;
            }
            else
                return null;
        }

 根据图片的相对路径 返回 BitmapImage对象的实例化:

        /// 
        /// 根据图片的相对路径 返回 BitmapImage对象的实例化
        /// 
        /// 图片的相对路径(如:@"/images/star.png")
        /// 
        public static BitmapImage GetBitmapImage(string imgPath)
        {
            try
            {
                if (!imgPath.StartsWith("/"))
                {
                    imgPath = "/" + imgPath;
                }
                return new BitmapImage(new Uri("Pack://application:,,," + imgPath));
            }
            catch
            {
                return null;
            }
        }

 根据图片的相对路径 获取ImageBrush对象:

      /// 
      /// 根据图片的相对路径 获取ImageBrush对象 (此对象资源可以直接用于绑定控件的Background属性)
      /// 
      /// 图片的相对路径(如:@"/images/star.png")
      /// 
        public static ImageBrush GetImageBrush(string imgPath)
        {
            if (File.Exists(imgPath))
            {
                ImageBrush ib = new ImageBrush();
                ib.ImageSource = GetBitmapImage(imgPath);
                return ib;
            }
            else
                return null;
        }

在Path中读取图片byte[]:

        /// 
        /// 根据图片的路径解析成图片资源
        /// 
        /// 
        /// 
        public static byte[] BitmapImageToByteArray(String filePath)
        {

            byte[] byteArray = null ;
            if(File.Exists(filePath))
                byteArray = File.ReadAllBytes(filePath);
            return byteArray;
        }

byte[]转BitmapImage:

        /// 
        /// 解析字节数组成图片
        /// 
        /// 
        /// 
        public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }
            return bmp;
        }

BitmapImage转byte[]:


        /// 
        /// 图片数据解析成字节流数组(用于存储到数据库)
        /// 
        /// 
        /// 
        public static byte[] BitmapImageToByteArray(BitmapImage bmp)
        {
            byte[] byteArray = null;
            try
            {
                Stream sMarket = bmp.StreamSource;
                if (sMarket != null && sMarket.Length > 0)
                {
                    sMarket.Position = 0;
                    using (BinaryReader br = new BinaryReader(sMarket))
                    {
                        byteArray = br.ReadBytes((int)sMarket.Length);
                    }
                }
            }
            catch
            {
            }
            return byteArray;
        }

将Bitmap对象转换成bitmapImage对象:

        /// 
        /// 将Bitmap对象转换成bitmapImage对象
        /// 
        /// 
        /// 
        public BitmapImage ConvertBitmapToBitmapImage(Bitmap bitmap)
        {
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Bmp);
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = stream;
            image.EndInit();
            return image;
        }

将bitmapImage对象转换成Bitmap对象:

        /// 
        /// 将bitmapImage对象转换成Bitmap对象
        /// 
        /// 
        /// 
        public static System.Drawing.Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
        {
            using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapImage));
                enc.Save(outStream);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
                return bitmap;
            }
        }

bitmap转换成ImageSource:

        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
        /// 
        /// 从bitmap转换成ImageSource
        /// 
        /// 
        /// 
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }

从Bitmap转换成BitmapSource:

        /// 
        /// 从Bitmap转换成BitmapSource
        /// 
        /// 
        /// 
        public static BitmapSource ChangeBitmapToBitmapSource(Bitmap bmp)
        {
            BitmapSource returnSource;
            try
            {
                returnSource = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
            catch
            {
                returnSource = null;
            }
            return returnSource;
        }

 从Icon到ImageSource的转换:

        /// 
        /// 从Icon到ImageSource的转换
        /// 
        public ImageSource ChangeIconToImageSource(Icon icon)
        {
            ImageSource imageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
            icon.Handle,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
            return imageSource;
        }

Stream保存图片:

FileStream fs = new FileStream("A.jpg", FileMode.Create, FileAccess.ReadWrite);
Stream MyStream = new MemoryStream((byte[])imageBytes); //取出的byte[]数组
int read = 0;
byte[] Mybyte = new byte[1024];
do
{
      read = MyStream.Read(Mybyte,0,1024);
      fs.Write(Mybyte,0,read);
} while (read > 0);
MyStream.Flush();
MyStream.Close();
fs.Flush();
fs.Close();

图片通过CGI获取保存到本地快照:

        public string Address = "url address";
        public void SavefromWeb()
        {
            FileStream fs = new FileStream("D:\\Image.jpg",FileMode.Create,FileAccess.ReadWrite);
            HttpWebRequest MyHttpWebRequest = null;
            HttpWebResponse MyHttpWebResponse = null;
            Stream MyStream = null;
            try
            {
                MyHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(Address);
                MyHttpWebResponse = (HttpWebResponse)MyHttpWebRequest.GetResponse();
                MyStream = MyHttpWebResponse.GetResponseStream();
            }
            catch(Exception)
            {
            }
            int read = 0;
            byte[] Mybyte=new byte[1024];
            do
            {
                read = MyStream.Read(Mybyte,0,1024);
                fs.Write(Mybyte,0,read);
            }while(read>0);
            MyStream.Flush();
            MyStream.Close();
            MyHttpWebResponse.Close();
            fs.Flush();
            fs.Close();
        }

参考:wpf 图片操作类 ImageBrush BitmapImage - ﹎蓝言觅ぷ雨 - 博客园

WPF(1)---图片的获取与存储 - Probably - 博客园

JPG PNG GIF BMP图片格式的区别_Wanda && Aidem -CSDN博客_bmp jpg png 区别

你可能感兴趣的:(WPF,C#,wpf,c#)