【问题标题】:convert image into base64 in wp8在wp8中将图像转换为base64
【发布时间】:2015-08-27 01:48:45
【问题描述】:

我有一张从我​​的手机图库中拍摄的图片,如下所示:

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;
    }
}

现在我想通过网络服务将此图像保存在数据库中。所以,我需要将此图像转换为 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;
    }
}

【问题讨论】:

  • @DGibbs:是的,请参阅我编辑的答案
  • C# 是一种区分大小写的语言
  • @DGibbs:命名空间“System”中不存在类型或命名空间名称“Drawing”(您是否缺少程序集引用?)
  • 但是哪个程序集?我不知道哪个适合溺水,它也会在“保存”中出错
  • @DGibbs:当时我想添加 system.drowing dll 时会出现错误“无法将对更高版本的引用或不兼容的程序集添加到项目中”我该如何解决问题

标签: c# image windows-phone-8 base64


【解决方案1】:

只需将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;
}

【讨论】:

  • 我正在使用此代码对图像进行编码以保存在 SQLite 数据库中,但是当我尝试解码时,我得到“FormatException”、“Base-64 char 数组或字符串的长度无效" 尝试从Base64String 转换时......知道为什么吗?
  • 如何将图像转换为 64 位并将 64 位转换为图像?
猜你喜欢
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多