简体   繁体   中英

convert image into base64 in wp8

I have an image taken from my phone gallery, like below:

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

Now I want to save this image in a database, via a web service. So, I'm required to convert this image into a base64 string, but how can I do this?

I've tried this, but it throws an exception:

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

Simply convert the byte[] to a 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 to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM