WPF Image控件 Source: Byte[] ,BitmapImage 相互轉換


文件轉為byte[]

FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
byte[] desBytes = new byte[fs.Length];
fs.Read(desBytes, 0, desBytes.Length);
fs.Close();  

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM