从image src中获取base64字符串

本文关键字:base64 字符串 获取 image src | 更新日期: 2023-09-27 17:59:31

我使用以下代码从image src中获取base64字符串,但它不起作用。

<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]);
    }
}

在控制器中,如何获取"imageValue"的值作为base64字符串?

目前我正在获取一个大字符串"imageValue"的值。

从image src中获取base64字符串

下面我粘贴了超过所需问题的内容。

一旦您选择了一个文件,这将获得Base64String,并将其显示在<div id="base"></div>中。

假设您想将文件存储在项目中,则保存功能也存在。:)

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>

首页控制器>转换动作

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

类将Base64String转换为文件

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

使用ajax/javascript尝试类似的操作。。。它将使用ajax数据参数将base64字符串发布到控制器,ajax数据参数作为datauri参数传递给控制器。

MyFunc会将图像转换为base64,并将其发布到一个动作中。

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');
        }
    });
}

在控制器中。。。MySaveAction将base64转换为位图,然后保存。

    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);
    }

帮助程序方法。。。这将提供ajax url参数所需的请求的完整限定路径。

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;
    }
}

最后,这是对base64字符串的修复。。。即,删除在使用JSON.Stringify.转换base64时插入的垃圾

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();
}