2013-04-26 75 views
0

我有我的手機畫廊拍攝,像下面的圖片:轉換成圖像的base64在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; 
    } 
} 
+0

@ DGibbs:是的,看到我編輯的答案 – MansinhDodiya 2013-04-26 10:57:25

+0

C#是一個** case-sensi tive **語言 – I4V 2013-04-26 11:11:34

+0

@DGibbs:命名空間'System'中不存在類型或命名空間名稱'Drawing'(您是否缺少程序集引用?) – MansinhDodiya 2013-04-26 11:18:05

回答

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

你能幫我在這裏http://stackoverflow.com/questions/23366212/convert-imagesource-to-base64string-wp8 – Goofy 2014-04-29 14:25:33

+0

我使用此代碼來編碼圖像保存在SQLite數據庫中,但是當我嘗試解碼時,當試圖轉換fromBase64String ....時,出現「FormatException」,「Base-64字符數組或字符串的長度無效」....任何ideia爲什麼? – 2015-11-23 17:02:59

+0

如何將圖像轉換爲64位和隱藏64位圖像? – 2016-12-05 13:18:33