Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8319385
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T22:18:40+00:00 2026-06-08T22:18:40+00:00

I’m having trouble creating an Image/Bitmap object in C# from a base64 encoded byte

  • 0

I’m having trouble creating an Image/Bitmap object in C# from a base64 encoded byte array.

Here’s what I’m dealing with:


I have a frontend where a user can crop an image. When the user selects an image via an input[type=file], my javascript code uses HTML5’s FileReader to save the DataUrl (base64 string) to a hidden field, that is posted along with the crop coordinates and dimensions, and everything else in that form.

The essence:

base64 data, if you want to test yourself:

http://kristianbak.com/test_image.txt

  1. base64 string is posted to the action, and received as the parameter imageData
  2. the action converts the string to a base64 byte array, like this:
  3. byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());

EncodeTo64 extension method:

public static string EncodeTo64(this String toEncode)
{
    var toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
    var returnValue = Convert.ToBase64String(toEncodeAsBytes);
    return returnValue;
}

After the base64 string is converted to a byte array, I read the bytes into the memory using a MemoryStream:

using (var imageStream = new MemoryStream(imageBytes, false))
{
    Image image = Image.FromStream(imageStream); //ArgumentException: Parameter is not valid.
}

I have also tried the following variations:

a)

using (var imageStream = new MemoryStream(imageBytes))
{
    Bitmap image = new Bitmap(imageStream); //ArgumentException: Parameter is not valid.
}

b)

using (var imageStream = new MemoryStream(imageBytes))
{
    imageStream.Position = 0;
    Image image = Image.FromStream(imageStream); //ArgumentException: Parameter is not valid.
}

c)

TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap image = (Bitmap)typeConverter.ConvertFrom(imageBytes);

d)

Using this method:

private Bitmap GetBitmap(byte[] buf)
{
    Int16 width = BitConverter.ToInt16(buf, 18);
    Int16 height = BitConverter.ToInt16(buf, 22);

    Bitmap bitmap = new Bitmap(width, height); //ArgumentException: Parameter is not valid.

    int imageSize = width * height * 4;
    int headerSize = BitConverter.ToInt16(buf, 10);

    System.Diagnostics.Debug.Assert(imageSize == buf.Length - headerSize);

    int offset = headerSize;
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            bitmap.SetPixel(x, height - y - 1, Color.FromArgb(buf[offset + 3], buf[offset], buf[offset + 1], buf[offset + 2]));
            offset += 4;
        }
    }
    return bitmap;
}

Conclusion:

I feel that there’s something else wrong, and I hope you can answer to this question.

Edit:

Sample of the frontend code:

<script>
    $(function() {
        var reader = new window.FileReader();

        function readImage(file, callBack) {
            reader.onload = function (e) {
                var image = new Image();
                image.onload = function (imageEvt) {
                    if (typeof callBack == "function") {
                        callBack(e.target.result);
                    }
                };
                image.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }

        $j('#file').change(function (e) {
            var file = e.target.files[0];

            readImage(file, function(imageData) {
                $('#imageData').val(imageData);
            });
        });
    });
</script>

@using (Html.BeginForm("UploadImage", "Images", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <input name="PostedImage.ImageData" type="hidden" id="imageData" value="" />

    @* REST OF THE HTML CODE HERE *@

    <p>Choose an image:</p>
    <input type="file" name="file" id="file" />

    <input type="submit" value="Upload" />
}

Sample of the Controller / Action:

[HttpPost]
public ActionResult Opret(PostedImage postedImage)
{
    String imageData = PostedImage.ImageData;

    byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());

    using (var imageStream = new MemoryStream(imageBytes, false))
    {
        Image image = Image.FromStream(imageStream);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T22:18:42+00:00Added an answer on June 8, 2026 at 10:18 pm

    I think your problem is that you are taking a base64 string that was posted to your controller , treating it like ASCII, and then converting it to base64 again.

    I think you need to change this line

    byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());
    

    to

    byte[] imageBytes = Convert.FromBase64String(imageData);
    

    from there your bytes should be correct and you should be able to create your image

    –Edit–

    I took the sample data you provided in the text document and parsed it before loading it into a Bitmap. I was able to save the image to my hard drive and was greeted by a Spartan (Go Green!!)

    Give this code a try and see what happens.

    Please note imageData is exactly what’s exposed on http://kristianbak.com/test_image.txt. I would have provided the initialization, but it’s a pretty big string and would probably break things.

    string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
    byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
    using ( var imageStream = new MemoryStream( imageBytes, false ) )
    {
       Bitmap image = new Bitmap( imageStream );
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a text area in my form which accepts all possible characters from
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a view passing on information from a database: def serve_article(request, id): served_article
I have a bunch of posts stored in text files formatted in yaml/textile (from
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.