使用 CryptoStream 将位图转换为 base 64 字符串格式

Converting bitmap to base 64 string format using CryptoStream

我希望return Base64字符串格式的图像新数据。

下面这些代码生成的图像文件格式不受支持

FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" +
    imageCounter.ToString() + "." + extension);
try
{
    RC2 crypt = RC2.Create();
    ICryptoTransform transform = crypt.CreateEncryptor();

    var output = new CryptoStream(File.Create(imageFileName.FullName),
        transform,
        CryptoStreamMode.Write);

    imageInfo.Bitmap.Save(output, imageFormat);
}

catch (System.Runtime.InteropServices.ExternalException)
{
    return null;
}

FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" +
    imageCounter.ToString() + "." + extension);
try
{
    RC2 crypt = RC2.Create();
    ICryptoTransform transform = crypt.CreateEncryptor();

    var output = new CryptoStream(File.Create(imageFileName.FullName),
        new ToBase64Transform(),
        CryptoStreamMode.Write);

    imageInfo.Bitmap.Save(output, imageFormat);
}

catch (System.Runtime.InteropServices.ExternalException)
{
    return null;
}

我该怎么做?

您应该使用 memory stream. You can then convert the stream to a byte array and feed into Convert.ToBase64 而不是保存到文件流。获取结果字符串并用它做任何你想做的事。

我从 this SO post here 中找到函数 PerformCryptography,它接受 ICryptoTransform 并且可以 return 结果作为 byte array

代码如下所示:

private void Start(object sender, EventArgs e)
{
    try
    {
        // Step 01: First load the Image and convert to a byte array
        var imgByteArray = File.ReadAllBytes(@"C:\someImage.jpg");

        // Step 02: Then encrypt & convert to a byte array
        RC2 crypt = RC2.Create();
        ICryptoTransform transform = crypt.CreateEncryptor();

        var cryptByteArray = PerformCryptography(transform, imgByteArray);

        // Step 03: Now convert the byte array to a Base64 String
        string base64String = Convert.ToBase64String(cryptByteArray);
    }

    catch (System.Runtime.InteropServices.ExternalException)
    {
        //return null;
    }
}

支持函数如下:

private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
        {
            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();
            return memoryStream.ToArray();
        }
    }
}