Get base64 string from src image

I used the below code to get base64 string from src image but it doesn't work.

<input type="file" name="fileUpload" id="fileUpload" onchange="showimagepreview(this)" />
<input type="hidden" id="imageValue" name="imageValue" />

      

function showimagepreview(input) {
    if (input.files && input.files[0]) {
        var filerdr = new FileReader();
        filerdr.onload = function (e) {
            $('#imgprvw').attr('src', e.target.result);

            $('#imageValue').val(e.target.result);
        }
        filerdr.readAsDataURL(input.files[0]);
    }
}

      

in controller, how to get 'imageValue' as base64 string?

I am currently getting the 'imageValue' of a large string.

+3


source to share


2 answers


Below I have inserted more than needed.

This will give Base64String, once you select the file, this will map it to <div id="base"></div>

.

Assuming you want to save the file in your project, the save function also exists. :)

Html

<input type='file' id="file-upload" />
<img id="img" src="" />
<div id="base"></div>
<button id="save">save</button>

      

JavaScript



<script>

    var base = '';

    function readImage(input) {
        if (input.files && input.files[0]) {
            var FR = new FileReader();
            FR.onload = function (e) {
                $('#img').attr("src", e.target.result);
                $('#base').text(e.target.result);
                base = e.target.result;
            };
            FR.readAsDataURL(input.files[0]);
        }
    }

    $("#file-upload").change(function () {
        readImage(this);
    });

    $('#save').on('click', function () {
        $.post('/Home/Convert', { 'Base64String': base }, function () { alert('Done'); });
    });


</script>

      

Home Controller> Convert Action

public void Convert(string Base64String)
{
    string fileName = "test.jpg";
    string rootpath = Server.MapPath(Path.Combine("~", "Image", fileName));
    ConvertBase64ToFile.ConvertToFile(rootpath, Base64String.Split(',')[1]);
}

      

Class for converting Base64String to file

public class ConvertBase64ToFile
{
    public static void ConvertToFile(string location, string file)
    {
        byte[] bytes = Convert.FromBase64String(file);
        File.WriteAllBytes(location, bytes);
    }
}

      

+1


source


Try something like this with ajax / javascript ... It will output the base64 string to the controller using the ajax data parameter which is passed to the controller as the datauri parameter.

MyFunc will convert the image to base64 and send it to the action.

function MyFunc() {
    con.drawImage(v, 0, 0, canvasWidth, canvasHeight);
    var = document.getElementById('imgprvw');
    dataURL = c.toDataURL('image/png');

    var raw_image_data = dataURL.replace(/^data\:image\/\w+\;base64\,/, '');

    $.ajax({
        url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'MySaveController/MySaveAction',
        type: 'POST', dataType: 'json',
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        data:
        {
            datauri: JSON.stringify(raw_image_data),
        },
        error: function (xhr) {
            alert('Error: ' + xhr.statusText);
        },
        success: function (result) {
            alert('Image Saved');
        }
    });
}

      

In the controller ... MySaveAction converts the base64 to a bitmap and then saves it.

    public ActionResult MySaveAction(string datauri)
    {
        // Some stuff.
        if (datauri.Length > 0)
        {
            Byte[] bitmapData = new Byte[datauri.Length];
            bitmapData = Convert.FromBase64String(FixBase64ForImage(datauri));

            string fileLocationImageName = "C:/MYIMAGE.JPG";

            MemoryStream ms = new MemoryStream(bitmapData);

            using (Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(ms)))
            {
                bitImage.Save(fileLocationImageName, System.Drawing.Imaging.ImageFormat.Jpeg);
                output = fileLocationImageName;
            }
        }

        return Json(output, JsonRequestBehavior.AllowGet);
    }

      



Helper method ... This will give the full request path which is required for the ajax url parameter.

public static class PathHelper
{
    public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
    {
        string appPath = string.Empty;

        if (httpRequestBase != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}",
                                    httpRequestBase.Url.Scheme,
                                    httpRequestBase.Url.Host,
                                    httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
                                    httpRequestBase.ApplicationPath);
        }

        if (!appPath.EndsWith("/"))
        {
            appPath += "/";
        }

        return appPath;
    }
}

      

Finally, this is the fix for the base64 string ... i.e. removes the crap that is inserted in base64 conversion using JSON.Stringify.

public string FixBase64ForImage(string image)
{
    System.Text.StringBuilder sbText = new System.Text.StringBuilder(image, image.Length);

    sbText.Replace("\r\n", String.Empty);
    sbText.Replace(" ", String.Empty);
    sbText.Replace("\"", String.Empty);

    return sbText.ToString();
}

      

0


source







All Articles