Mad coder.
Mad coder.

Reputation: 2175

C# Image uploading using FileUpload

I found the following code but unable to understand what should I pass through ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format).

I need a FileUpload tool to upload an image to system and to pass it to ImageToBase64

For reference my code is

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

I tried doing ImageToBase64(FileUpload.FileBytes, "Image/PNG") But I am getting syntax error. What's the correct syntax that I can use to this code?

Upvotes: 0

Views: 2310

Answers (2)

3Dave
3Dave

Reputation: 29071

As the method signature states, the second parameter is of type ImageFormat. This is an enumeration, so you'd use it like so:

/// create or load a bitmap
var bitmap = new Bitmap(.....);

var base64string = ImageToBase64(bitmap,ImageFormat.Bmp);

In this case, the ImageFormat parameter is apparently used to tell the Save() method what format you'd like the data in (jpeg, png, bmp, etc). The MIME type is insufficient, and doesn't really belong in this context since this method isn't web-specific.

Upvotes: 0

jishi
jishi

Reputation: 24634

Because the function takes argument of type Image and ImageFormat, and you are passing in byte[] and string.

You don't need mime type, and you would only need the

var base64String = Convert.ToBase64String(FileUpload.FileBytes);

Upvotes: 6

Related Questions