簡體   English   中英

Base64 編碼字節數組的有效方法?

[英]An efficient way to Base64 encode a byte array?

我有一個byte[]並且我正在尋找對它進行 base64 編碼的最有效方法。

問題是內置的 .Net 方法Convert.FromBase64CharArray需要char[]作為輸入,而將我的byte[]轉換為char[]只是為了將其再次轉換為 base64 編碼數組似乎很愚蠢。

有沒有更直接的方法來做到這一點?

[[編輯:]]我會解釋我想要更好的實現 - 我有一個byte[] ,我需要返回一個新的base64編碼byte[]

字節[] -> 字符串:使用system.convert.tobase64string

Convert.ToBase64String(byte[] data)

字符串 -> 字節 []:使用system.convert.frombase64string

Convert.FromBase64String(string data)

Base64 是一種以文本形式(作為字符串)表示字節的方法。 所以沒有 Base64 編碼的 byte[] 這樣的東西。 您將有一個base64 編碼的 string ,您可以解碼byte[]

但是,如果你想得到一個字節數組,你可以使用 base64 編碼的字符串並將其轉換為一個字節數組,例如:

string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);

然而,這是沒有意義的,因為將 byte[] 表示為 byte[] 的最佳方式是 byte[] 本身:)

下面是將 base64 直接編碼為字節數組的代碼(測試為執行 +-10% 的 .Net 實現,但分配了一半的內存):

    static public void testBase64EncodeToBuffer()
    {
        for (int i = 1; i < 200; ++i)
        {
            // prep test data
            byte[] testData = new byte[i];
            for (int j = 0; j < i; ++j)
                testData[j] = (byte)(j ^ i);

            // test
            testBase64(testData);
        }
    }

    static void testBase64(byte[] data)
    {
        if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
    }

    static public byte[] appendBase64(byte[] data
                              , int offset
                              , int size
                              , bool addLineBreaks = false)
    {
        byte[] buffer;
        int bufferPos = 0;
        int requiredSize = (4 * ((size + 2) / 3));
        // size/76*2 for 2 line break characters    
        if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);

        buffer = new byte[requiredSize];

        UInt32 octet_a;
        UInt32 octet_b;
        UInt32 octet_c;
        UInt32 triple;
        int lineCount = 0;
        int sizeMod = size - (size % 3);
        // adding all data triplets
        for (; offset < sizeMod;)
        {
            octet_a = data[offset++];
            octet_b = data[offset++];
            octet_c = data[offset++];

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
            if (addLineBreaks)
            {
                if (++lineCount == 19)
                {
                    buffer[bufferPos++] = 13;
                    buffer[bufferPos++] = 10;
                    lineCount = 0;
                }
            }
        }

        // last bytes
        if (sizeMod < size)
        {
            octet_a = offset < size ? data[offset++] : (UInt32)0;
            octet_b = offset < size ? data[offset++] : (UInt32)0;
            octet_c = (UInt32)0; // last character is definitely padded

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];

            // add padding '='
            sizeMod = size % 3;
            // last character is definitely padded
            buffer[bufferPos - 1] = (byte)'=';
            if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
        }
        return buffer;
    }
byte[] base64EncodedStringBytes = Encoding.ASCII.GetBytes(Convert.ToBase64String(binaryData))

根據您的編輯和評論……這就是您所追求的嗎?

byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));

您可以使用 String Convert.ToBase64String(byte[]) 將字節數組編碼為 base64 字符串,然后使用 Byte[] Convert.FromBase64String(string) 將結果字符串轉換回字節數組。

要將圖像從字節檢索到 base64 字符串....

模型屬性:

    public byte[] NomineePhoto { get; set; }

    public string NomineePhoneInBase64Str 
    {
        get {
            if (NomineePhoto == null)
                return "";

            return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
        } 
    }

在視圖中:

   <img style="height:50px;width:50px" src="@item.NomineePhoneInBase64Str" />
    public void ProcessRequest(HttpContext context)
    {
        string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        MemoryStream str = new MemoryStream();

        context.Response.Clear();
        Byte[] bytes = (Byte[])dr[0];
        string d = System.Text.Encoding.Default.GetString(bytes);
        byte[] bytes2 = Convert.FromBase64String(d);
        //context.Response.Write(d);
        Image img = Image.FromStream(new MemoryStream(bytes2));
        img.Save(context.Response.OutputStream, ImageFormat.Png);
        context.Response.Flush();
        str.WriteTo(context.Response.OutputStream);
        str.Dispose();
        str.Close();
        conn.Close();
        context.Response.End();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM