简体   繁体   中英

Silverlight 4 : Converting image into byte[]

I have found how to do this in .NET 4.0, but I think JpegBitmapEncoder doesn't exist in Silverlight:

MemoryStream memStream = new MemoryStream();              
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
var bytes = memStream.GetBuffer();

How can I convert an image to bytes[] in silverlight?

UPDATE:

I have a Contact model, which has a Photo property. Whenever I add a new Contact, I would like to load a local default Image and convert it and set the Photo property to it.

var bitmapImage = new BitmapImage
                            {
                                UriSource = new Uri("pack://application:,,,/xxx;component/Images/default.JPG")
                            };
            var image = new Image{Source = bitmapImage};

Is this the correct way to load an image in first place?

Use

myImage.Save(memStream, ImageFormat.Jpeg);
return memStream.ToArray();

UPDATE

OK it turns out that the image is a BitmapImage .

It seems that BitmapImage does not expose the functionality to save the image. The solution is to get the image from the embedded resource:

Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);

Have a look at this library: Imagetools

It contains some nice utilities and jpg and png encoders,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM