在wp8中将图像转换为base64
本文关键字:转换 base64 图像 wp8 | 更新日期: 2023-09-27 18:11:11
我从我的手机图库中取了一张图片,如下所示:
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;
}
}
现在我想通过web服务将此图像保存在数据库中。我需要将这个图像转换为base64字符串,但我该怎么做呢?
我试过了,但是它抛出了一个异常:
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;
}
}
简单地将byte[]
转换为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;
}