Reputation: 73
I am using this code
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myimage);
wb.SaveJpeg(ms, myimage.PixelWidth, myimage.PixelHeight, 0, 100);
byte [] imageBytes = ms.ToArray();
from Convert image to byte array on Windows Phone 7 No System.Drawing Dll any other way? but WriteableBitmap does not contain SaveJpeg method in Windows phone 8.1 environment.
Upvotes: 4
Views: 6746
Reputation: 4359
On Windows Phone 8.1 Silverlight applications your code works fine, I assume that myImage
is a BitmapImage
. The only thing just must do is to wait for the BitmapImage
to load completly:
using System.IO;
using System.Windows.Media.Imaging;
...
myImage = new BitmapImage(new Uri("https://i.sstatic.net/830Ke.jpg?s=128&g=1", UriKind.Absolute));
myImage.CreateOptions = BitmapCreateOptions.None;
myImage.ImageOpened += myImage_ImageOpened;
...
void myImage_ImageOpened(object sender, RoutedEventArgs e)
{
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
}
I just tested that code and it works perfectly on WP8.1.
But as you commented on another post you can't reference Microsoft.Phone
, you are probably doing a Windows Phone 8.1 Store App, in which case you can use the following code:
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
...
BitmapImage bitmapImage = new BitmapImage(new Uri("https://i.sstatic.net/830Ke.jpg?s=128&g=1"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
Upvotes: 3
Reputation: 29792
I suspect that you are targeting Windows Runtime Apps as you haven't found the namespace suggested in this answer (which will work for WP8.1 Silverlight).
In Windows Runtime apps you can use Encoder
- the sample code can look like this:
// lets assume that you have your image in WriteableBitmap yourWb
using (MemoryStream ms = new MemoryStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms.AsRandomAccessStream());
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
imageWidth,
imageHeight,
horizontalDPI,
verticalDPI,
yourWb.PixelBuffer.ToArray());
await encoder.FlushAsync();
}
Upvotes: 2
Reputation: 18257
SaveJpeg is an extension method (http://msdn.microsoft.com/en-US/library/windowsphone/develop/system.windows.media.imaging.extensions.savejpeg(v=vs.105).aspx). Have you referenced Microsoft.Phone
in your project references and added using System.Windows.Media.Imaging;
to your .cs file?
Upvotes: 0