【问题标题】:在 WPF 中存储和检索二进制图像
【发布时间】:2014-07-02 21:13:40
【问题描述】:

我已将数据库中的图像保存为二进制:

 Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
        if (fd.ShowDialog() == true)
        {
            ILogo.Source = new BitmapImage(new Uri(fd.FileName));

            Stream stream = File.OpenRead(fd.FileName);
            binaryImage = new byte[stream.Length];
            stream.Read(binaryImage, 0, (int)stream.Length);
        }
           _merchantInfo.Logo = binaryImage;

我想读取图像并显示它的图像工具,我试过这个:

        _merchantInfo = new MerchantInfo();
        _merchantInfo = _context.MerchantInfo.FirstOrDefault();

        byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
        Stream stream = new MemoryStream(binaryPhoto);
        _merchantLogo = new BitmapImage();
        _merchantLogo.StreamSource = stream;

        ILogo.Source = _merchantLogo;

没有错误,但图像没有显示在图像框中:(

我的代码有错误吗?

谢谢。

【问题讨论】:

  • 您是否在应用程序的其他地方使用了 try/catch,这可能会捕获此代码中的异常?
  • 这与您之前的问题有何不同?请编辑那个并添加更多关于你想要达到的目标的详细信息。
  • @Clemens,这是不同的问题!!但无论如何我已经解决了这个问题,我会添加最终答案。感谢任何方式
  • 好的,但是说真的,你需要提供更多关于你想要做什么的细节。
  • 我会的,谢谢克莱门斯 :)

标签: c# wpf


【解决方案1】:

通用二进制存储方法 -> 必须读取图片/文件的所有字节,并将它们保存在二进制数组中。

OpenFileDialog FileDialog = new OpenFileDialog();

byte[] BinaryData = new byte[]{};

if(FileDialog.ShowDialog())
{
   BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
}


二进制检索(仅适用于 WPF 中的图像)-> 您必须设置一个 BitmapImage 并在 MemoryStream 的帮助下将所有二进制信息存储在其中。

BitmapImage image = new BitmapImage();
byte[] binary = new byte{}; /* <--- The array where 
                            we stored the binary 
                            information of the picture*/

image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(binary)
image.EndInit();

通用二进制检索和二进制文件上传方法->

byte[] BinaryData = new byte[]{};

private void Download()
{
   OpenFileDialog FileDialog = new OpenFileDialog();

   if(FileDialog.ShowDialog())
   {
     BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
   }
}

private void Save()
{
   OpenFileDialog FileDialog = new SaveFileDialog();

   if(FileDialog.ShowDialog())
   {
     using(System.IO.Stream stream = new File.Open(FileDialog.FileName, FileMode.Create))
     {
           using (var BinaryWriter = new BinaryWriter(stream))
           {
                                                    
               BinaryWriter.Write(BinaryData);
               BinaryWriter.Close();
           }
     }
   }
    
   
}

【讨论】:

    【解决方案2】:

    我终于解决了这个问题,这里是在数据库中以二进制形式存储和检索图像的代码:

    要存储图像:

           Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
            if (fd.ShowDialog() == true)
            {
                ILogo.Source = new BitmapImage(new Uri(fd.FileName));
    
                Stream stream = File.OpenRead(fd.FileName);
                binaryImage = new byte[stream.Length];
                stream.Read(binaryImage, 0, (int)stream.Length);
            }
    
            _merchantInfo.Logo = binaryImage;
            _context.SaveChanges();
    

    图像检索与显示:

            merchantInfo = new MerchantInfo();
            _merchantInfo = _context.MerchantInfo.FirstOrDefault();
    
            byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
            Stream stream = new MemoryStream(binaryPhoto);
            _merchantLogo = new BitmapImage();
            _merchantLogo.BeginInit();
            _merchantLogo.StreamSource = stream;
            _merchantLogo.EndInit();
            ILogo.Source = _merchantLogo;
    

    感谢大家帮助我:)

    【讨论】:

      【解决方案3】:

      我创建了这个类,我正在使用它没有任何问题,尝试并分享它。

      /// <summary>
      /// created by Henka Programmer.
      /// Class to make the converting images formats and data structs so easy.
      /// This Class supporte the following types:
      /// - BtimapImage, 
      /// - Stream,
      /// - ByteImage
      /// 
      /// and the other option is image resizing.
      /// </summary>
      
      public class Photo
      {
      public BitmapImage BitmapImage;
      public System.IO.Stream Stream;
      public byte[] ByteImage;
      
      public Photo(Uri PhotoUri)
      {
      
          this.BitmapImage = new BitmapImage(PhotoUri);
          this.Stream = new MemoryStream();
          this.Stream = this.BitmapImage.StreamSource;
          this.ByteImage = StreamToByteArray(this.Stream);
      
      }
      public Photo(Bitmap Photo_Bitmap)
          : this((ImageSource)(new ImageSourceConverter().ConvertFrom(Photo_Bitmap)))
      {
          /*
          ImageSourceConverter c = new ImageSourceConverter();
      
          byte[] bytes = (byte[])TypeDescriptor.GetConverter(Photo_Bitmap).ConvertTo(Photo_Bitmap, typeof(byte[]));
          Photo ph = new Photo(bytes);*/
      }
      public Photo(ImageSource PhotoSource) : this(PhotoSource as BitmapImage) { }
      public Photo(BitmapImage BitmapPhoto)
      {
      
          this.BitmapImage = BitmapPhoto;
          this.ByteImage = GetByteArrayFromImageControl(BitmapPhoto);
          this.Stream = new MemoryStream();
          WriteToStream(this.Stream, this.ByteImage);
      }
      public Photo(string path)
      {
      
          try
          {
              this.Stream = System.IO.File.Open(path, System.IO.FileMode.Open);
              this.BitmapImage = new BitmapImage();
              BitmapImage.BeginInit();
              BitmapImage.StreamSource = Stream;
              BitmapImage.EndInit();
              this.ByteImage = StreamToByteArray(this.Stream);
      
          }
          catch (Exception exception)
          {
              Debug.WriteLine(exception.Message);
          }
      }
      
      public Photo(byte[] byteimage)
      {
      
          this.ByteImage = new byte[byteimage.Length];
          this.ByteImage = byteimage;
          // WriteToStream(this.Stream, this.ByteImage);
          //MemoryStream ms = new MemoryStream(byteimage);
          this.Stream = new MemoryStream(byteimage);
      }
      
      private void WriteToStream(Stream s, Byte[] bytes)
      {
          using (var writer = new BinaryWriter(s))
          {
              writer.Write(bytes);
          }
      }
      
      private byte[] StreamToByteArray(Stream inputStream)
      {
          if (!inputStream.CanRead)
          {
              throw new ArgumentException();
          }
      
          // This is optional
          if (inputStream.CanSeek)
          {
              inputStream.Seek(0, SeekOrigin.Begin);
          }
      
          byte[] output = new byte[inputStream.Length];
          int bytesRead = inputStream.Read(output, 0, output.Length);
          Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
          return output;
      }
      
      private BitmapImage BitmapImageFromBytes(byte[] bytes)
      {
          BitmapImage image = new BitmapImage();
          using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
          {
              imageStream.Write(ByteImage, 0, ByteImage.Length);
              imageStream.Seek(0, System.IO.SeekOrigin.Begin);
              image.BeginInit();
              image.CacheOption = BitmapCacheOption.OnLoad;
              image.StreamSource = imageStream;
              image.EndInit();
              //image.Freeze();
      
          }
          return image;
      }
      
      public BitmapImage GetResizedBitmap(int width, int height)
      {
      
          ImageSource imgSrc = CreateResizedImage(this.ByteImage, width, height);
          return new Photo(GetEncodedImageData(imgSrc, ".jpg")).BitmapImage;
      }
      
      private ImageSource CreateResizedImage(byte[] imageData, int width, int height)
      {
      
          BitmapImage bmpImage = new BitmapImage();
      
          bmpImage.BeginInit();
      
          if (width > 0)
          {
      
              bmpImage.DecodePixelWidth = width;
      
          }
      
          if (height > 0)
          {
      
              bmpImage.DecodePixelHeight = height;
      
          }
      
          bmpImage.StreamSource = new MemoryStream(imageData);
      
          bmpImage.CreateOptions = BitmapCreateOptions.None;
      
          bmpImage.CacheOption = BitmapCacheOption.OnLoad;
      
          bmpImage.EndInit();
      
          Rect rect = new Rect(0, 0, width, height);
      
          DrawingVisual drawingVisual = new DrawingVisual();
      
          using (DrawingContext drawingContext = drawingVisual.RenderOpen())
          {
      
              drawingContext.DrawImage(bmpImage, rect);
      
          }
      
          RenderTargetBitmap resizedImage = new RenderTargetBitmap(
      
          (int)rect.Width, (int)rect.Height, // Resized dimensions
      
          96, 96, // Default DPI values
      
          PixelFormats.Default); // Default pixel format
      
          resizedImage.Render(drawingVisual);
      
          return resizedImage;
      }
      
      internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)
      {
      
          byte[] returnData = null;
      
          BitmapEncoder encoder = null;
      
          switch (preferredFormat.ToLower())
          {
      
              case ".jpg":
      
              case ".jpeg":
      
                  encoder = new JpegBitmapEncoder();
      
                  break;
      
              case ".bmp":
      
                  encoder = new BmpBitmapEncoder();
      
                  break;
      
              case ".png":
      
                  encoder = new PngBitmapEncoder();
      
                  break;
      
              case ".tif":
      
              case ".tiff":
      
                  encoder = new TiffBitmapEncoder();
      
                  break;
      
              case ".gif":
      
                  encoder = new GifBitmapEncoder();
      
                  break;
      
              case ".wmp":
      
                  encoder = new WmpBitmapEncoder();
      
                  break;
      
          }
      
          if (image is BitmapSource)
          {
      
              MemoryStream stream = new MemoryStream();
      
              encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
      
              encoder.Save(stream);
      
              stream.Seek(0, SeekOrigin.Begin);
      
              returnData = new byte[stream.Length];
      
              BinaryReader br = new BinaryReader(stream);
      
              br.Read(returnData, 0, (int)stream.Length);
      
              br.Close();
      
              stream.Close();
      
          }
      
          return returnData;
      
      }
      
      public byte[] GetByteArrayFromImageControl(BitmapImage imageC)
      {
          MemoryStream memStream = new MemoryStream();
          JpegBitmapEncoder encoder = new JpegBitmapEncoder();
          encoder.Frames.Add(BitmapFrame.Create(imageC));
          encoder.Save(memStream);
          return memStream.GetBuffer();
      }
      
      public ImageSource ToImageSource()
      {
          ImageSource imgSrc = this.BitmapImage as ImageSource;
          return imgSrc;
      }
      
      public System.Windows.Controls.Image ToImage()
      {
          System.Windows.Controls.Image Img = new System.Windows.Controls.Image();
          Img.Source = this.ToImageSource();
          return Img;
      
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 2021-03-26
        • 2012-05-25
        相关资源
        最近更新 更多