Im very new to this site. Its my first question! hope somone knows the answer.
Here is the deal, I have a database with entities that hold a byte array as a picture (one of the entity properties).
here is the code that convets the pic to byte[] before saving it to the DB:
public async Task<byte[]> ImageFileToByteArrayAsync(StorageFile file)
{
IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
return pixelData.DetachPixelData();
}
when I pull the entity from the database I see that it comes with the correct data of the picture as byte[].
Im working on a windows 8.1 app and with mvvmCross. in my viewModel I have a full prop named selectedGuest. this property holds the current Guest. all the info about the guest is succsessfuly transformed to the UI accept the image! here is the xaml of the image:
<Image Grid.Column="2" Source="{Binding SelectedGuest.Image, Converter={StaticResource ByteArrayToImageConverter}}"/>
and here is the converter:
public class ByteArrayToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null || !(value is byte[]))
return null;
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])value);
writer.StoreAsync().GetResults();
}
BitmapImage image = new BitmapImage();
image.DecodePixelHeight = 200;
image.DecodePixelWidth = 150;
image.SetSource(stream);
return image;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
when debuging the thread ENTERS the converter and the 'value' is correct! but somhow I cant see the image. nothing apears, the image just wont display.
thanks for the viewers!
You should store the original encoded image buffer (i.e. the binary image file content) in your database, not the raw pixel data:
public async Task<byte[]> ImageFileToByteArrayAsync(StorageFile file)
{
var buffer = await FileIO.ReadBufferAsync(file);
return buffer.ToArray();
}
Related
I am working on an application for Windows phone 8.1 in Xamarin with mvvmCross. I need to select multiple images from the phone library and display them. I am using FileOpenPicker.SelectMultipleFilesAndContinue to do so. Now i need to be able to display all these images in the view. One problem is that the minimum amount of images must be 20 and the images could be pretty large.
First i tried making them into byte arrays and used a converter to display them.
public async void SelectFotosCallback(FileOpenPickerContinuationEventArgs args) {
if (args.Files.Count > 0) {
foreach (StorageFile file in args.Files) {
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
byte[] bytes = null;
using (var reader = new DataReader(fileStream.GetInputStreamAt(0))) {
bytes = new byte[fileStream.Size];
await reader.LoadAsync((uint)fileStream.Size);
reader.ReadBytes(bytes);
}
callback(bytes);
}
}
else {
}
}
This method did seem to work at the first try but as soon as I tried it with 5 images it stopped working. When it was done with the callback the app just quit. No error message or anything. (My guess is an overload in memory.)
After this i found a little solution where i take the byte arrays and make them to Xamarin.Form Images.
public async void SelectFotosCallback(FileOpenPickerContinuationEventArgs args) {
if (args.Files.Count > 0) {
foreach (StorageFile file in args.Files) {
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
byte[] bytes = null;
using (var reader = new DataReader(fileStream.GetInputStreamAt(0))) {
bytes = new byte[fileStream.Size];
await reader.LoadAsync((uint)fileStream.Size);
reader.ReadBytes(bytes);
}
Image image = new Image();
image.Source = ImageSource.FromStream(() => new MemoryStream(bytes));
var iets = image.Source.BindingContext;
callback(image);
}
}
else {
}
This seemed to take care of the problem for the overload in memory. the only other problem now is that i can not seem to find any way the display these images.
<GridView ItemsSource="{Binding SelectedImages}">
<GridView.ItemTemplate>
<DataTemplate>
<Grid>
<Image Style="{StaticResource imageListImage}" Source="{Binding Source}"/>
<Button Style="{StaticResource imageListXButton}">
<Button.Background>
<ImageBrush ImageSource="ms-appx:///Resources/XButton.png"/>
</Button.Background>
</Button>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
I try to display them with a simple binding. I have not found any way that would work. Does anyone know a way to display these Images and if not what would be the best alternative to use the bytes without using too much memory.
After some deep digging I was able to find the answer. It was a lot simpeler than I thought. I started working with the decodepixel from the BitmapImage. Using a coneverter I set the values.
public object Convert(object value, Type targetType, object parameter, string language) {
BitmapImage image = (BitmapImage)value;
image.DecodePixelType = DecodePixelType.Logical;
if (image.PixelHeight >= image.PixelWidth) {
image.DecodePixelHeight = 100;
}
else {
image.DecodePixelWidth = 100;
}
return image;
}
The weird thing was that it did work some of the time. But for some reason it didn't work on all the image and it sometimes even threw them away.
But after a lot of testing i finally found what I was looking for.
BitmapImage bitmap = new BitmapImage();
BitmapImage temp = new BitmapImage();
bitmap.DecodePixelType = DecodePixelType.Logical;
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) {
IRandomAccessStream secondStream = fileStream.CloneStream();
BitmapImage temp = new BitmapImage();
temp.SetSource(fileStream);
if (temp.PixelHeight >= temp.PixelWidth) {
bitmap.DecodePixelHeight = 150;
}
else {
bitmap.DecodePixelWidth = 150;
}
bitmap.SetSource(secondStream);
}
For some reason setting the decodepixel after setting the source makes it inconsitent but setting these values before setting the source actually crops the image right away.
This method works perfectly and completely resolves my outofmemory problem
My WP7 app has an Image control whose Source is set in XAML to an image with its Build Action set to Content:
<Image x:Name="MyImage" Source="/Images/myimage.png"/>
I need to store this image in my SqlCe database as a byte array. This is my current code to convert to byte[]:
public byte[] ImageToArray() {
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri( "/Images/myimage.png", UriKind.Relative );
WriteableBitmap wbmp = new WriteableBitmap( image );
return wbmp.ToArray();
}
The byte array saves to the database, but when I retrieve and my converter tries to convert it back (on a different page), I get "unspecified error." This is my converter:
public class BytesToImageConverter : IValueConverter {
public object Convert( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
if( Value != null && Value is byte[] ) {
byte[] bytes = Value as byte[];
using( MemoryStream stream = new MemoryStream( bytes ) ) {
stream.Seek( 0, SeekOrigin.Begin );
BitmapImage image = new BitmapImage();
image.SetSource( stream ); // Unspecified error here
return image;
}
}
return null;
}
public object ConvertBack( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
throw new NotImplementedException( "This converter only works for one way binding." );
}
}
I've done quite a bit of searching. As far as the converter, my code is pretty standard. I've seen mention that stream.Position = 0; is necessary, but my understanding is stream.Seek is doing the same thing; I've tried both.
As my converter is the same I've used in about a dozen projects now, I'm fairly convinced the problem lies in converting the Image control's Source to a byte array and thus my image data is corrupted. In the code above I'm hard coding the Uri, but I've also tried
BitmapImage image = MyImage.Source as BitmapImage;
without luck. I've been at this for hours and at my wit's end. What am I missing?
I think the problem is in your ImageToArray() method. You are converting your WriteableBitmap object to array, but not the image itself. Try by replacing your method with the following:
public byte[] ImageToArray()
{
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri("/Images/myimage.png", UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wbmp.SaveJpeg(ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
return ms.ToArray();
}
This methd writes the image to a stream as jpg, and returns it bytes. I haven't tried the code, but you shouldn't have problem to convert it back to a BitmapImage using your converter.
The byte[] from image.UriSource may be base64 radix.You can browse byte[] or data in the SQL tale.
If radix is wrong,can not reverse to stream from byte[].So if radix is 64,must convert to 16 radix.
I have a ListBox with Image :
<Image Margin="0" Source="{Binding Path=ImgUrl}" HorizontalAlignment="Stretch" Width="80" Height="80"
Tag="{Binding idStr}" OpacityMask="{x:Null}" Stretch="Fill"/>
And i want that when i bind it it will save the image to my disk for cache issues,and the next time it will check if the image exist and take it from the disk. It is possible to do something like this?
Download image-> Save to disk -> make image as image source
You could use a specialized binding converter that saves each image to file.
The sample code below shows the basic structure of such a converter. You will have to add some error handling and of course you need to define a mapping from image URIs to local file paths. You may also support System.Uri as alternative source type.
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var result = value;
var imageUrl = value as string;
if (imageUrl != null)
{
var buffer = (new WebClient().DownloadData(imageUrl));
if (buffer != null)
{
// create an appropriate file path here
File.WriteAllBytes("CachedImage.jpg", buffer);
var image = new BitmapImage();
result = image;
using (var stream = new MemoryStream(buffer))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
You would use that converter in your binding like this:
<Image Source="{Binding Path=ImgUrl,
Converter={StaticResource ImageConverter}}" ... />
I have some troubles with saving a image from memorystream.
Here is my code:
MemoryStream ms = new MemoryStream(onimg);
if (ms.Length > 0)
{
Bitmap bm = new Bitmap(ms);
returnImage = (Image)bm.Clone();
}
ms.Close();
returnImage.Save(#"C:\img.jpeg");
And on returnImage.Save i have the following exception:
A generic error occurred in GDI+.
If I do not close the MemoryStream all is OK but that requires lot of memory after some time.
How can I do this?
EDIT:That Save is only demonstration.. I really need returnImage for place it in ObservableCollection and display in window when i Need it convert to System.Windows.Media.Imaging.BitmapImage();
[ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// empty images are empty...
if (value == null) { return null; }
var image = (System.Drawing.Image)value;
// Winforms Image we want to get the WPF Image from...
var bitmap = new System.Windows.Media.Imaging.BitmapImage();
bitmap.BeginInit();
MemoryStream memoryStream = new MemoryStream();
// Save to a memory stream...
image.Save(memoryStream, ImageFormat.Bmp);
// Rewind the stream...
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
bitmap.StreamSource = memoryStream;
bitmap.EndInit();
return bitmap;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
And XAML when i do this
<DataTemplate>
<Image Width="32" Height="32" Source="{ Binding Thumb, Converter={StaticResource imageConverter} }" />
</DataTemplate>
According to documentation:
You must keep the stream open for the lifetime of the Bitmap.
Bitmap needs to store its data samewhere, and I deduce (although have no proof for this) that Bitmap does not copy the data, instead using the stream, keeping a lock on it.
Also, there is no evidence that Clone will create new bitmap with the copy of byte representation. And your testcase suggests it is not a case.
Therefore, I am afraid you need to keep your stream open for the lifetime of your image. It requires memory, true, but otherwise if Bitmap copied the data, you will still need that memory for the bitmap representation. Therefore, no more memory is consumed with open stream (if my previous deduction was true).
If you really want to overcome the bitmap's dependency on the original memory stream, you will need to draw the orginal bitmap on the new one instead of cloning like here.
But this will impact the performance, I would better re-analyze if it is not a good idea to keep the original stream, just making sure it is closed when bitmap is disposed.
Isn't a save to disk basically a clone?
using (MemoryStream ms = new MemoryStream(onimg))
{
if (ms.Length > 0)
{
using (Bitmap bm = new Bitmap(ms))
{
bm.Save(#"C:\img.jpeg");
}
}
}
Currently I'm working on a Ultrasound scanning project, which displays the continues images aquired from a probe, to do that I'm writing following code.
XAML:
<Image Name="imgScan" DataContext="{Binding}" Source="{Binding Path=prescanImage,Converter={StaticResource imgConverter}}" />
C# Assignment:
Bitmap myImage = GetMeImage();
imageMem = new MemoryStream();
myImage .Save(imageMem, ImageFormat.Png);
imgScan.DataContext = new { prescanImage = imageMem.ToArray() };
Converter:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value is byte[])
{
byte[] ByteArray = value as byte[];
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = new MemoryStream(ByteArray);
bmp.EndInit();
return bmp;
}
return null;
}
This method is costing me lot of (performance),
is there any better way to do it??
Since you're already setting the DataContext in code (not xaml), why not just skip a few steps?
Bitmap myImage = GetMeImage();
imageMem = new MemoryStream();
myImage.Save(imageMem, ImageFormat.Png);
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = new MemoryStream(imageMem.ToArray());
bmp.EndInit();
imgScan.Source = bmp;
If you have access to GetMeImage(), you may want to consider altering it to better fit into your application - Does it really need to return a Bitmap?
Also, how often is your first piece of code being executed? You may want to consider altering that, or allowing it to vary when it needs to.