C # convert the image and BASE64 strings .,

Source: Internet
Author: User

C # convert the image and BASE64 strings .,

1 using System; 2 using System. collections. generic; 3 using System. drawing; 4 using System. IO; 5 using System. linq; 6 using System. web; 7 using System. drawing. imaging; 8 // blog garden aC # Coder sort 9 namespace Html5Image. tools10 {11 public class ImageTool12 {13 // convert the image to base64 encoded text 14 public static string ImgToBase64String (Bitmap bmp) 15 {16 // Bitmap bmp = new Bitmap (Imagefilename ); 17 // this. pictureBox1.Image = Bmp; 18 // FileStream fs = new FileStream (Imagefilename + ". txt ", FileMode. create); 19 // StreamWriter sw = new StreamWriter (fs); 20 21 MemoryStream MS = new MemoryStream (); 22 bmp. save (MS, System. drawing. imaging. imageFormat. jpeg); 23 byte [] arr = new byte [ms. length]; 24 ms. position = 0; 25 ms. read (arr, 0, (int) ms. length); 26 ms. close (); 27 String strbaser64 = Convert. toBase64String (arr); 28 29 return strba Ser64; 30} 31 32 public static Bitmap Base64StringToImage (string base64Img) 33 {34 byte [] bytes = Convert. fromBase64String (base64Img); 35 MemoryStream ms = new MemoryStream (); 36 ms. write (bytes, 0, bytes. length); 37 Bitmap bmp = new Bitmap (MS); 38 39 return bmp; 40} 41 42 // <summary> 43 // Save the image 44 // </summary> 45 // <param name = "base64Img"> </param> 46 // <param name = "imgPath"> </param> 47 // <param nam E = "imgFormat"> EX: System. drawing. imaging. jpeg </param> 48 public static void SaveFile (string base64Img, string imgPath, ImageFormat imgFormat) 49 {50 string dir = Path. getDirectoryName (imgPath); 51 if (! Directory. exists (dir) 52 {53 Directory. createDirectory (dir); 54} 55 var bitmap = Base64StringToImage (base64Img); 56 bitmap. save (imgPath, imgFormat); 57} 58} 59}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.