我有一张从我的手机图库中拍摄的图片,如下所示:
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;
}
}