Convert an image to base64 and vice versa

后端 未结 2 821
时光取名叫无心
时光取名叫无心 2021-01-18 07:23

I want to convert an image to base64 and back to image again. Here is the code which i tried so far and the error also. Any suggestions please?

public void Ba         


        
相关标签:
2条回答
  • 2021-01-18 08:10

    The MemoryStream.Read Method reads bytes from the MemoryStream into the specified byte array.

    If you want to write the byte array to the MemoryStream, use the MemoryStream.Write Method:

    ms.Write(imageBytes, 0, imageBytes.Length);
    ms.Seek(0, SeekOrigin.Begin);
    

    Alternatively, you can simply wrap the byte array in a MemoryStream:

    MemoryStream ms = new MemoryStream(imageBytes);
    
    0 讨论(0)
  • 2021-01-18 08:25

    You are reading from an empty stream, rather than loading the existing data (imageBytes) into the stream. Try:

    byte[] imageBytes = Convert.FromBase64String(coded);
    using(var ms = new MemoryStream(imageBytes)) {
        finalImage = System.Drawing.Image.FromStream(ms);
    }
    

    Also, you should endeavour to ensure that finalImage is disposed; I would propose:

    System.Drawing.Image finalImage = null;
    try {
        // the existing code that may (or may not) successfully create an image
        // and assign to finalImage
    } finally {
        if(finalImage != null) finalImage.Dispose();
    }
    

    And finally, note that System.Drawing is not supported on ASP.NET; YMMV.

    Caution

    Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

    0 讨论(0)
提交回复
热议问题