locked
Converting bitmap to base 64 string format using CryptoStream RRS feed

  • Question

  • User-1453200658 posted

    Hello there,

    I wish to return the new data of the image in Base64 string format.

    These codes below generate image file format not supported

    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;
    }
    

    or

    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;
    }
    

    How can I do this?

    Sunday, February 14, 2021 4:24 PM

Answers

  • User-939850651 posted

    Hi Edward Sheriff Curits,

    I wish to return the new data of the image in Base64 string format.

    These codes below generate image file format not supported

    I'm not sure what kind of result you will get with the code you provided, I think it should be the same result as the method you mentioned in another thread:

    imageInfo.Bitmap.Save(imageFileName.FullName, imageFormat);
        byte[] imageBytes = memoryStream.ToArray();
        string base64String = Convert.ToBase64String(imageBytes);

    Do you add such a prefix mark in front of this base64 string? The base64 format string obtained in the program does not contain these contents, you need to add it manually.

    data:image/png;base64,

    result:

    Hope this can help you. 

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 15, 2021 9:03 AM