我的手机图库中有一张图片,如下所示:
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;
}
}
答案 0 :(得分:5)
只需将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到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;
}