I am doing an application for windows phone 7.
the application is access a image from database(Sql server 2008).
the data is stored in data type 'image'.I want to Display the image.
i use the following code
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
byte[] data;
BitmapImage empImage = new BitmapImage();
Stream mm;
data = (byte[])value;
mm = new MemoryStream(data);
mm.Position = 0;
BinaryReader BR = new BinaryReader(mm);
byte[] image=BR.ReadBytes(data.Length);
mm = new MemoryStream(image);
//empImage.SetSource(mm);
return empImage;
}
But there is a 'Unspecified' error at commented line (empImage.SetSource(mm);).
Please help Me......
BitmapImage.SetSource accepts a Stream (you can leave out the CreateOptions if you don't need to access the bytes immediately afterwards):
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
byte[] data = (byte[])value;
using (MemoryStream stream = new MemoryStream(data))
{
BitmapImage image = new BitmapImage
{
CreateOptions = BitmapCreateOptions.None
};
image.SetSource(stream);
return image;
}
}
Also, I don't think an IValueConverter is the right place for this sort of code.
And finally, the image database type has been deprecated in favour of varbinary(MAX)
Related
I have an Entry which is binded two way with nullable decimals and has numeric keyboard. Everything is ok except I cannot use decimal point. Whenever I press . (dot) from keyboard, UI does not accept it. Do you guys have any idea? Online search did not help me. Thanks. BTW, I use Android Emulator.
I found out that if I change property from nullable to non-nullable (i.e decimal? to decimal) then UI accepts decimal point. Do you guys have any idea why? Why UI does not allow to enter decimal point when the binding property is nullable?
This is because the value is not recognized with a defined type while it is incomplete (editing).
You can use a converter (String to double) like this:
>
public class DoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
return (double)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
string stringValue = value as string;
if (string.IsNullOrEmpty(stringValue))
return null;
double dbl;
if (double.TryParse(stringValue, out dbl))
{
if(dbl == 0)
{
return null;
}
return dbl;
}
return null;
}
}
Reference:
https://forums.xamarin.com/discussion/60719/xamarin-forms-binding-nullable-double-to-entry
I am using itext7 for PDF manipulation. I am trying to fill form fields by field.setValue method. My _Reader object is filled at constructor level and is used on Adding and Getting form fields. But on Saving form field value, on closing PdfDocument object following exception is caught:
at System.IO.__Error.StreamIsClosed()
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at iText.IO.Source.OutputStream`1.Write(Byte[] b, Int32 off, Int32 len)
at iText.IO.Source.OutputStream`1.WriteInteger(Int32 value)
at iText.Kernel.Pdf.PdfWriter.WriteToBody(PdfObject pdfObj)
at iText.Kernel.Pdf.PdfWriter.FlushObject(PdfObject pdfObject, Boolean
canBeInObjStm)
at iText.Kernel.Pdf.PdfDocument.FlushObject(PdfObject pdfObject, Boolean
canBeInObjStm)
at iText.Kernel.Pdf.PdfObject.Flush(Boolean canBeInObjStm)
at iText.Kernel.Pdf.PdfPage.Flush(Boolean flushResourcesContentStreams)
at iText.Kernel.Pdf.PdfPage.Flush()
at iText.Kernel.Pdf.PdfDocument.Close()
Code snippet is as following:
using (var memoryStream = new MemoryStream())
{
PdfDocument document = new PdfDocument(_Reader, new PdfWriter(memoryStream));
PdfAcroForm Form = PdfAcroForm.GetAcroForm(document, true);
foreach (PDFField Field in PDFFields)
{
PdfFormField formField = Form.GetField(Field.Name);
switch (Field.Type)
{
case PDF_FIELD_TYPE.TEXTBOX:
if (!string.IsNullOrEmpty(Field.Value))
formField.SetValue(Field.Value);
else
formField.SetValue(string.Empty);
break;
}
}
document.Close();
byte[] PDFBytes = ((MemoryStream)memoryStream).ToArray();
Thanks in advance for help.
I have a ListView item which contains datas and images from a http GET request. I can display all of data in the ListView, except the picture. For getting the image I have to make a separate http GET request. I can display an image with this code:
private async void DisplayPicture()
{
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(App.answer.picture);
await dataWriter.StoreAsync();
ims.Seek(0);
BitmapImage bitmap = new BitmapImage();
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmap.SetSource(ims);
}
But this doesn't work if I would like to use in a ListView with Binding.
Here is the code what I tried:
public class BinaryToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value != null && value is byte[])
{
var bytes = value as byte[];
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
//await dataWriter.StoreAsync();
ims.Seek(0);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(ims);
//var ims = new MemoryStream(bytes);
//var image = new BitmapImage();
//image.SetSource(stream);
//stream.Close();
return bitmap;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
The main problem is that I get the image in byte[] (bytearray) from the server, and only the above code can display it on WP8.1. So I have to use the dataWriter.StoreAsync() method, but if I use it, I have to use async, which must be void. But the void return value is not good for me due to the binding.
You can see the original code what I uncommented, but I cannot use it, because the input value for image.SetSource() must be a RandomAccessStream. So I don't have any idea how I can solve this problem.
If you want to make binding and use asynchronous method, then one way to make it work is to set DataContext to Task and bind to its Result. Stepen Cleary wrote a nice article about that. You will also find some useful information in his answer here.
Basing on that answer I've build a sample, which I think you can modify to fulfill your needs. Write a Converter which will return TaskCompletionNotifier (see Stephen's answer above):
public class WebPathToImage : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return null;
// the below class you will find in Stephen's answer mentioned above
return new TaskCompletionNotifier<BitmapImage>(GetImage((String)value));
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{ throw new NotImplementedException(); }
private async Task<BitmapImage> GetImage(string path)
{
HttpClient webCLient = new HttpClient();
var responseStream = await webCLient.GetStreamAsync(path);
var memoryStream = new MemoryStream();
await responseStream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(memoryStream.AsRandomAccessStream());
return bitmap;
}
}
then you can define binding in XAML:
<Image DataContext="{Binding ImageFromWeb, Converter={StaticResource WebPathToImage}}" Stretch="Uniform"
Source="{Binding Result}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="2"/>
Everything should work when you set ImageFromWeb:
ImageFromWeb = #"http://www.onereason.org/wp-content/uploads/2012/02/universe-300x198.jpg";
I am working on Windows 8 store application. I am new at it.
I am receiving an image in the form of byte array (byte []).
I have to convert this back to Image and display it in Image Control.
so far I have button and Image control on Screen. When I click button, I call following function
private async Task LoadImageAsync()
{
byte[] code = //call to third party API for byte array
System.IO.MemoryStream ms = new MemoryStream(code);
var bitmapImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Windows.Storage.Streams.DataWriter write = new Windows.Storage.Streams.DataWriter(imras.GetOutputStreamAt(0));
write.WriteBytes(code);
await write.StoreAsync();
bitmapImg.SetSourceAsync(imras);
pictureBox1.Source = bitmapImg;
}
This is not working properly. any idea?
When I debug, I can see the byte array in ms. but it is not getting converted to bitmapImg.
I found the following on Codeproject
public class ByteImageConverter
{
public static ImageSource ByteToImage(byte[] imageData)
{
BitmapImage biImg = new BitmapImage();
MemoryStream ms = new MemoryStream(imageData);
biImg.BeginInit();
biImg.StreamSource = ms;
biImg.EndInit();
ImageSource imgSrc = biImg as ImageSource;
return imgSrc;
}
}
This code should work for you.
You can try something like that:
public object Convert(object value, Type targetType, object parameter, string language)
{
byte[] rawImage = value as byte[];
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])rawImage);
// The GetResults here forces to wait until the operation completes
// (i.e., it is executed synchronously), so this call can block the UI.
writer.StoreAsync().GetResults();
}
BitmapImage image = new BitmapImage();
image.SetSource(ms);
return image;
}
}
I found the following answer in another thread (Image to byte[], Convert and ConvertBack). I used this solution in a Windows Phone 8.1 project, not sure about Windows Store apps, but I believe it will work.
public object Convert(object value, Type targetType, object parameter, string culture)
{
// Whatever byte[] you're trying to convert.
byte[] imageBytes = (value as FileAttachment).ContentBytes;
BitmapImage image = new BitmapImage();
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length);
ms.Seek(0);
image.SetSource(ms);
ImageSource src = image;
return src;
}
I have been using the sql ce to bring some data onto my application. Now I need to add some of the images to make it look pretty. What all I want to know is
There must be some image to byte conversion done,
Retrieve the image byte code and convert back into the image.
I've got stuck at the second part and how am I supposed to continue?
Any links or examples are needed for the reference.
Thanks a lot.
Here's some ideas I have used in the past.
The image column in the DB:
[Column]
public byte[] MyImage
{
get { return _myImage; }
set
{
if (_myImage != value)
{
_myImage = value;
NotifyPropertyChanging("MyImage");
NotifyPropertyChanged("MyImage");
}
}
}
Save image:
public void AddNewImage(Stream image, string url)
{
byte[] byteArray = GetImageBytes(image);
var item = new MyDatabaseItem { Count = 1, ItemImageUrl = url, MyImage = byteArray };
MyDatabaseItemModel.Add(item);
MyDatabaseDB.MyDatabaseItems.InsertOnSubmit(item);
MyDatabaseDB.SubmitChanges();
}
Get image:
private byte[] GetImageBytes(Stream stream)
{
using (var ms = new MemoryStream())
{
var writeableBitmap = PictureDecoder.DecodeJpeg(stream, 200, 200);
writeableBitmap .SaveJpeg(ms, 200, 200, 0, 30);
return ms.ToArray();
}
}
Using a value converter:
public class ImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is byte[])
{
var memoryStream = new MemoryStream(value as byte[]);
varwriteBitmap = PictureDecoder.DecodeJpeg(memoryStream, 200, 200);
return writeBitmap;
}
else
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And finally bind it in XAML:
<Image Source="{Binding MyImage, Converter={StaticResource ImageConverter}}" Stretch="UniformToFill"/>