Reputation: 1435
I have an image taken from my phone gallery, like below:
private void StackPanel_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
PhotoChooserTask pct = new PhotoChooserTask();
pct.Show();
pct.Completed += pct_Completed;
}
void pct_Completed(object sender, PhotoResult e)
{
BitmapImage img = new BitmapImage();
if (e.ChosenPhoto != null)
{
img.SetSource(e.ChosenPhoto);
imgphotochoser.Source = img;
}
}
Now I want to save this image in a database, via a web service. So, I'm required to convert this image into a base64 string, but how can I do this?
I've tried this, but it throws an exception:
public string imagetobase64(image image,
system.drawing.imaging.imageformat format)
{
using (memorystream ms = new memorystream())
{
// convert image to byte[]
image.save(ms, format);
byte[] imagebytes = ms.toarray();
// convert byte[] to base64 string
string base64string = convert.tobase64string(imagebytes);
return base64string;
}
}
Upvotes: 0
Views: 2982
Reputation: 417
Simply convert the byte[]
to a base64 string
:
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
if (imgphotochoser.Source != null)
{
WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)imgphotochoser.Source);
wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
bytearray = ms.ToArray();
}
}
string str = Convert.ToBase64String(bytearray);
Base64 to byte[]
:
byte[] fileBytes = Convert.FromBase64String(s);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
Upvotes: 5