有时要实现BitmapImage与byte[]相互转换,这里实现两个静态方法,直接调用即可。

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)
        {
            
//很重要,因为Position经常位于Stream的末尾,导致下面读取到的长度为0。
            sMarket.Position = 0;

            
using (BinaryReader br = new BinaryReader(sMarket))
            {
                byteArray
= br.ReadBytes((int)sMarket.Length);
            }
        }
    }
    
catch
    {
        
//other exception handling
    }

    
return byteArray;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2022-12-23
  • 2021-12-16
  • 2021-09-07
  • 2022-02-22
  • 2021-08-16
猜你喜欢
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-05-31
  • 2021-05-22
相关资源
相似解决方案