Timothy
Timothy

Reputation: 3

Converting from Image to Base64 returns Error

I am trying to convert an image into a base64 String so i can save in a column in my database. Now i see this method

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
    using (MemoryStream ms = new MemoryStream())
    {
        // Convert Image to byte[]
        image.Save(ms, format);
        byte[] imageBytes = ms.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

And it gives me an Error in ASP.NET saying it does not contain the definition for Save , asks if i am missing an Assembly reference. And when i call it in the main method like this

string base64ImageString = ImageToBase64(img, System.Drawing.Imaging.ImageFormat.Jpeg);

of which the main code looks like this now :

        sigObj.SetImageFileFormat(0);
        sigObj.SetImageXSize(500);
        sigObj.SetImageYSize(150);
        sigObj.SetImagePenWidth(8);
        sigObj.SetJustifyX(5);
        sigObj.SetJustifyY(5);
        sigObj.SetJustifyMode(5);
        System.Drawing.Image img = sigObj.GetSigImage();
        base64ImageString = ImageToBase64(img, System.Drawing.Imaging.ImageFormat.Jpeg);

It gives me another funny error there which looks like this

Cannot convert from System.Drawing.Image to System.Web.UI.Web.Controls.Image

Please what exactly am I doing wrong. I am doing this on ASP.NET webform

Upvotes: 0

Views: 873

Answers (2)

Barry O'Kane
Barry O'Kane

Reputation: 1187

The last error tells you exactly what the issue is.

In the code file you have a reference to System.Web.UI.Web.Controls.Image, so in the method signature your reference to Image image is actually referring to that package.

You can test this by hovering over the reference and you should see the full path as above.

The reference that you actually need (and that contains the Save() method that you're trying to use is System.Drawing.Image.

Upvotes: 0

Gaurav
Gaurav

Reputation: 902

The declaration of your method is getting clashed with System.Drawing.Image and System.Web.UI.Controls. Use it like

public string ImageToBase64(System.Drawing.Image image,System.Drawing.Imaging.ImageFormat format)

Upvotes: 0

Related Questions