簡體   English   中英

在wp8中將圖像轉換為base64

[英]convert image into base64 in wp8

我從手機圖庫中拍攝了一張圖片,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM