zoukankan      html  css  js  c++  java
  • 二进制数据和字符串之间转换

    1.把二进制数据编码为base64格式

    你有一个byte[]用于表示一些二进制信息,比如图像,你需要把这些数据编码为一个字符串,以便可以通过不适合二进制的方式(比如电子邮件)发送它。

    可以使用Convert类的静态方法Convert.ToBase64String,把byte[]编码为string

            public static string Base64EncodeBytes(this byte[] inputBytes)
            {
                return Convert.ToBase64String(inputBytes);
            }

    2.解码base64编码的二进制数据

           public static byte[] Base64DecodeString(this string inputStr)
            {
                return Convert.FromBase64String(inputStr);
            }

    3.把图像文件编码为字符串

            public static string EncodeImageToString(string imageFilePath)
            {
                byte[] image = null;
                FileStream fstrm = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
                using (BinaryReader reader = new BinaryReader(fstrm))
                {
                    image = new byte[reader.BaseStream.Length];
                    for (int i = 0; i < reader.BaseStream.Length; i++)
                    {
                        image[i] = reader.ReadByte();
                    }
                }
                return image.Base64EncodeBytes();
            }

    4.测试

           static void Main(string[] args)
            {
                string imageAsString = Base64Convert.EncodeImageToString(@"sport.jpg");
                string imageFile = AppDomain.CurrentDomain.BaseDirectory + "test.png";
                byte[] imageBytes = imageAsString.Base64DecodeString();
                FileStream fstrm = new FileStream(imageFile, FileMode.Create, FileAccess.Write);
                using(BinaryWriter writer = new BinaryWriter(fstrm))
                {
                    writer.Write(imageBytes);
                }
            }
  • 相关阅读:
    Servlet细节
    https协议
    常用css缩写
    Servlet
    计算机编码总结
    java 中 finally 语句块的 深度解析 总结
    使用DIV之后 table何去何从
    http协议
    web开发基础
    js闭包之我见
  • 原文地址:https://www.cnblogs.com/marshhu/p/7247876.html
Copyright © 2011-2022 走看看