简体   繁体   中英

Get base64 string from image src

I have used the below code to get base64 string from image src, but it is not working.

<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 the controller, how to get the value of 'imageValue' as a base64 string?

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

Below I have pasted more than the question required.

This will get the Base64String once you have selected a file, this will display it in the <div id="base"></div> .

Assuming you want to store the file in your project, the save functionality is there as well. :)

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 to convert the Base64String to a File

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

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

MyFunc will convert an image to base64 and post it to an 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 will convert the base64 to a bitmap and then save 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 qualified path of the request that 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 a fix for the base64 string... ie removes crap that is inserted when you convert base64 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM