2010-03-15 34 views
16
public Image Base64ToImage(string base64String) 
    { 
     // Convert Base64 String to byte[] 
     byte[] imageBytes = Convert.FromBase64String(base64String); 
     MemoryStream ms = new MemoryStream(imageBytes, 0, 
      imageBytes.Length); 

     // Convert byte[] to Image 
     ms.Write(imageBytes, 0, imageBytes.Length); 
     System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); 
     return image; 
    } 

Tôi muốn chuyển đổi byte [] thành hình ảnh, tuy nhiên System.Drawing.Image không được hỗ trợ trong Silverlight. Bất kỳ thay thế nào?Silverlight 4.0: Làm thế nào để chuyển đổi byte [] thành hình ảnh?

Trả lời

22

Bạn cần tạo một ImageSource và gán cho Image control hoặc sử dụng ImageBrush để đặt ở chế độ nền. BitmapImage nằm trong không gian tên System.Windows.Media.Imaging.

 byte[] imageBytes = Convert.FromBase64String(base64String); 
     using (MemoryStream ms = new MemoryStream(imageBytes, 0, 
      imageBytes.Length)) 
     { 
      BitmapImage im = new BitmapImage(); 
      im.SetSource(ms); 
      this.imageControl.Source = im; 
     } 

hoặc cho ImageBrush

 byte[] imageBytes = Convert.FromBase64String(base64String); 
     using (MemoryStream ms = new MemoryStream(imageBytes, 0, 
      imageBytes.Length)) 
     { 
      BitmapImage im = new BitmapImage(); 
      im.SetSource(ms); 
      imageBrush.ImageSource = im; 
      this.BoxBorder.Background = imageBrush; 
     } 
+1

Tại sao bạn cần phải viết các imageBytes để MemoryStream bằng cách sử dụng phương thức Write? Họ không phải từ ctor? Không nên im.SetSource (luồng) im.SetSource (ms)? – DaveB

+0

Oh yea, tôi chỉ sử dụng lại mã gốc mà anh ta đã ở trên để thuận tiện, nhưng bây giờ nhìn vào nó - nó là một chút đi. – nyxtom

0

Một cách khác:

public static BitmapImage ConvertStreamToImage(Stream stream) 
    { 
     BitmapImage _resultImage = new BitmapImage(); 

     _resultImage.SetSource(stream); 

     return _resultImage; 
    } 

trong đó sử dụng những không gian tên: using System.IO; using System.Windows.Media.Imaging;

3

mã này có thể chuyển đổi hình ảnh để byte []

BitmapImage imageSource = new BitmapImage(); 
Stream stream = openFileDialog1.File.OpenRead(); 
BinaryReader binaryReader = new BinaryReader(stream); 
currentImageInBytes = new byte[0]; 

currentImageInBytes = binaryReader.ReadBytes((int)stream.Length); 
stream.Position = 0; 
imageSource.SetSource(stream); 

và mã này có thể chuyển đổi byte [] để hình ảnh

public void Base64ToImage(byte[] imageBytes) 
{ 

    using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) 
    { 
     BitmapImage im = new BitmapImage(); 
     im.SetSource(ms); 
     img.Source = im; 
    } 
} 
Các vấn đề liên quan