Image与Base64字符串相互转换

public class Form1 : System.Windows.Forms.Form

{

    private string GetBase64String(System.Drawing.Image image)

    {

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

 

        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        byte[] buffer = ms.ToArray();

 

        return Convert.ToBase64String(buffer);

    }

    private string FixBase64ForImage(string ImageText)

    {

        System.Text.StringBuilder sbText = new System.Text.StringBuilder(ImageText, ImageText.Length);

        sbText.Replace("/r/n", String.Empty);

        sbText.Replace(" ", String.Empty);

        return sbText.ToString();

    }

 

    private Image GetImageFromBase64String(string ImageText)

    {

        if (ImageText.Length > 0)

        {

            Byte[] bitmapData = new Byte[ImageText.Length];

 

            //bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));

            bitmapData = Convert.FromBase64String(ImageText);

            System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);

            //    Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));

            return Image.FromStream(streamBitmap);

        }

        else

        {

            return null;

        }

    }

 

 

 

    //===============

 

    void Button3Click(object sender, System.EventArgs e)

    {

        string str = GetBase64String(pictureBox1.Image);

        richTextBox1.Text = str;

        pictureBox1.Image = null;

    }

 

    void Button4Click(object sender, System.EventArgs e)

    {

        pictureBox1.Image = GetImageFromBase64String(richTextBox1.Text);

    }

}

你可能感兴趣的:(image,base64,类型装换)