Windows Phone 8.1 Runtime - Image to byte[] and Vice Versa - windows-runtime

For my application, I am trying to convert an WriteableBitmap to byte[] to store in the database, and then from byte[] to BitmapImage to display back to the user.
My current methods that so far, produce no results:
public byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
using (Stream stream = bitmap.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
To convert from byte array to BitmapImage, I use:
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])buffer);
writer.StoreAsync().GetResults();
}
var image = new BitmapImage();
image.SetSource(ms);
imageByteTest.Source = image;
}
There is good documentation for Silverlight applications I have found, but very little in the way for Windows Store Universal Runtime Applications. Where are these methods going wrong?

You might want to take a look at the WriteableBitmapEx library which contains some extensions to WriteableBitmap, as well as some core features like your conversion of WriteableBitmap to byte array and vice versa.

I wrote a converter for ByteArrayToBitmapImage:
public object Convert(object value, Type targetType, object parameter, string language)
{
var byteArray = value as byte[];
var bitmapImage = new BitmapImage();
Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
using (var stream = new MemoryStream(byteArray))
{
bitmapImage.SetSourceAsync(stream.AsRandomAccessStream());
}
});
return bitmapImage;
}
And byte[] -> WriteableBitmap
public static WriteableBitmap PrepareWritableBitmap(Size size, byte[] pixels)
{
uint height = (uint)Math.Floor(size.Height);
uint width = (uint)Math.Floor(size.Width);
WriteableBitmap bmp = new WriteableBitmap((int)width, (int)height);
Stream pixStream = bmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, (int)(width * height * 4));
//4 is a channel number for RGBA, for RGB is 3 channels
return bmp;
}

Related

JSON.NET: getting json from external source with streams, how to get just one value?

I have the following code:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
//What do I do here to get my one value?
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:
[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]
I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?
You could try the following
using System;
using System.Net.Http;
using Newtonsoft;
public class Program {
public static void Main() {
var client = new HttpClient();
var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
var data = JsonConvert.DeserializeObject<dynamic>(json);
string value = data[0].co2_uitstoot_gecombineerd;
Console.WriteLine(value);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}

Windows phone can't save CookieContainer

I apologize for my english :)
I catch cookies from server. And try to save it in order to use cookeis later.
var Settings = IsolatedStorageSettings.ApplicationSettings;
CookieContainer _Cookie = new CookieContainer()
_Cookie.Add(new Uri("http://www.portal.fa.ru/Job/SearchResultDiv"), response.Cookies);
Settings.Clear();
Settings["UserID"] = userID;
Settings["Cookie"] = _Cookie;
Settings.Save();
Ok it working. But after restart app cookie has losted. (Object has remain but cookies count = 0). I don't know.
So i try to convert from CookieContainer to array byte than save and load it when i need it.
public static byte[] ToByte(CookieContainer data)
{
byte[] CookieByte;
DataContractSerializer serializer = new DataContractSerializer(typeof(CookieContainer));
using (var memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, data);
CookieByte = memoryStream.ToArray();
}
return CookieByte;
}
public static CookieContainer FromByte(byte[] data)
{
CookieContainer Cookie;
DataContractSerializer serializer = new DataContractSerializer(typeof(CookieContainer));
using (var memoryStream = new MemoryStream(data))
{
Cookie = (CookieContainer)serializer.ReadObject(memoryStream);
}
return Cookie;
}
But this code did not work again. When i convert to byte and back i losing cookies (count = 0).
So what can i do?
PS write pls your code when you deal with authorization and cookies. Thx

get URI of image stored in isolatedstorage

i have saved a file named 'logo.jpg' in the isolatedstorage using this code...
private void step2_Click(object sender, RoutedEventArgs e)
{
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
try
{
WriteableBitmap wb = new WriteableBitmap(img);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
catch { }
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
NavigationService.Navigate(new Uri("/Stage2.xaml?num="+Contact_number.Text+"&name="+contact_name.Text, UriKind.Relative));
}
and creating tile using this function..
private StandardTileData GetSecondaryTileData()
{
string filePath = System.IO.Path.Combine(#"/Shared/ShellContent", "logo.jpg");
StandardTileData tileData = new StandardTileData
{
Title = name,
BackgroundImage = new Uri(#"isostore:" + filePath, UriKind.Absolute),
Count = 0,
BackTitle = "app",
BackBackgroundImage = new Uri("", UriKind.Absolute),
BackContent = "content"
};
but it is throwing an exception
"An exception of type 'System.UriFormatException' occurred in System.ni.dll but was not handled in user code
Additional information: Invalid URI: The URI is empty."
the problem was that image was not in the shared/shellcontent/ and also
BackBackgroundImage = new Uri("", UriKind.Absolute),
this is incorrect. it should be relative if the tile has to be kept blank... took so many hours. huff
use this
MediaLibraryExtension.GetPath(p);
here p is the object of Class Picture(that is the picture for which it will return the path)

C# - Emgu Cv - Face Recognition- Loading training sets of Faces saved to Access database as a binary in to EigenObjectRecognizer for Face recognition

I was having a hard time loading training set from Ms Access database in to the main form that does the Face Recognition. I saved the training sets with their names and ID in to the database as a binary data with an OLE Object format.The method i used to change, save and read the data from the database and in to the training sets is
private static byte[] ConvertImageToBytes(Image InputImage)
{
using (Bitmap BmpImage = new Bitmap(InputImage))
{
using (MemoryStream MyStream = new MemoryStream())
{
BmpImage.Save(MyStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] ImageAsBytes = MyStream.ToArray();
return ImageAsBytes;
}
}
}
The method that i use to store the converted byte data to the database is the following:
private void StoreData(byte[] ImageAsBytes,String NameStudent,String IDStudent)
{
if (DBConnection.State.Equals(ConnectionState.Closed))
DBConnection.Open();
try
{
//MessageBox.Show("Saving image at index : " + rowPosition);
using (OleDbCommand insert = new OleDbCommand(String.Format("Insert INTO
TrainingSet(rowPosition,StudentName,StudentID,StudentFace) values ('
{0}','{1}','{2}',#StudentFace)", rowPosition, NameStudent, IDStudent),
DBConnection))
{
OleDbParameter imageParameter = insert.Parameters.AddWithValue(#"StudentFace",
SqlDbType.Binary);
imageParameter.Value = ImageAsBytes;
imageParameter.Size = ImageAsBytes.Length;
int rowsAffected = insert.ExecuteNonQuery();
MessageBox.Show(String.Format("Data stored successfully in {0}
Row",rowsAffected));
}
rowPosition++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.Message);
}
finally
{
RefreshDBConnection();
}
}
The method that i use to Read this binary data is as follows:
private Image ReadImageFromDB()
{
Image FetchedImg;
if (rowNumber >= 0)
{
byte[] FetchedImgBytes = (byte[])LocalDataTable.Rows[rowNumber]["StudentFace"];
MemoryStream stream = new MemoryStream(FetchedImgBytes);
FetchedImg = Image.FromStream(stream);
return FetchedImg;
}
else
{
MessageBox.Show("There are no images in the database yet.Please reconnect
or add some pictures.");
return null;
}
}
I have successfully saved the training sets/images as a binary data in to the database.The problem is when i load these training sets for Recognition.
// Declaring the variables=====trainingImages is where the training sets are
// loaded from the database NameLabels and IDLabels are text in the database
// and where name and Id of subject
//is saved.
List<Image<Gray,byte>> trainingImages = new List<Image<Gray,byte>>();
List<string> NameLables= new List<string>();
List<string> IDLables = new List<string>();
int ContTrain, NumNameLabels,NumIDLabels, t;
//The training sets from the database are loaded in to the facerecognizer code as
// follows
public FaceRecognizer()
{
InitializeComponent();
try
{
//Load previous trained and labels for each image from the database Here
RefreshDBConnection();
String[] NameLabels = (String[])LocalDataTable.Rows[rowNumber]["StudentName"];
NumNameLabels = Convert.ToInt16(NameLabels[0]);
String[] IDLabels = (String[])LocalDataTable.Rows[rowNumber]["StudentID"];
NumIDLabels = Convert.ToInt16(IDLabels[0]);
if (NumNameLabels == NumIDLabels)
{
ContTrain = NumNameLabels;
string LoadFaces;
// Converting the master image to a bitmap
Image imageFromDB;
Bitmap imageChangedToBitmap;
// Normalizing it to grayscale
Image<Gray, Byte> normalizedMasterImage;
for (int tf = 1; tf < NumNameLabels + 1; tf++)
{
imageFromDB = ReadImageFromDB();
//image loaded from the database is converted in to Bitmap and then
//convert the bitmap image in to Image<Gray,byte> for input to
//EigenObjectRecognizer(,,,)
imageChangedToBitmap = new Bitmap(imageFromDB);
normalizedMasterImage = new Image<Gray, Byte>(imageChangedToBitmap);
LoadFaces = String.Format("face{0}.bmp", tf);
trainingImages.Add(normalizedMasterImage);
//trainingImages.Add(new Image<Gray, byte>());
NameLables.Add(NameLabels[tf]);
IDLables.Add(IDLabels[tf]);
rowNumber = rowNumber + 1;
}
}
else
MessageBox.Show("There's a conflict between Name labels and id labels");
}
catch (Exception e)
{
MessageBox.Show("Nothing in the database, please add at least a
face.Train the database","Triained faces load",MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
I am only getting the message in the catch when the the form loads even if there are faces saved in the database. I have used EigenObjectRecognizer and i will post the code if necessary.
at the part of loading face, you did not save by face1, face2, face3 etc. So you can not load using;
LoadFaces = String.Format("face{0}.bmp", tf);

Convert Byte Array into List Windows phone 8

I am using this piece of code to convert List into byte array but again I want to convert to this data into List how it is possible.
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();
In your example it isn't possible, because you have no way to tell where a string ends and where the next one starts. It would be possible by using a separator (the character \0 is often used to indicate the end of a string):
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + '\0').ToArray();
You can then retrieve your list by using the Split method:
var stringList = System.Text.Encoding.UTF8.GetString(byteArr, 0, byteArr.Length).Split('\0');
But overall I don't think it's a good idea. Depending on what you need, I'd rather recommend to use the DataContractSerializer to convert your array to bytes:
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<string>));
byte[] byteArr;
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, stringlist);
byteArr = ms.ToArray();
}
And to convert it back:
using (var ms = new System.IO.MemoryStream(byteArr))
{
stringlist = (Sserializer.ReadObject(ms);
}