C# - 无论我尝试什么,Base64 字节数组到图像都会失败

2024-03-25

我在 C# 中从 Base64 编码的字节数组创建图像/位图对象时遇到问题。

这是我正在处理的事情:


我有一个用户可以裁剪图像的前端。当用户通过选择图像input[type=file],我的javascript代码使用HTML5的FileReader来保存DataUrl(base64 字符串)到 ahidden field,与裁剪坐标和尺寸以及其中的其他所有内容一起发布form.

精华:

base64数据,如果你想自己测试一下:

http://kristianbak.com/test_image.txt http://kristianbak.com/test_image.txt

  1. base64 字符串被发布到操作,并作为参数接收imageData
  2. 该操作将字符串转换为 Base64 字节数组,如下所示:
  3. byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());

EncodeTo64扩展方法:

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

将 base64 字符串转换为字节数组后,我使用 a 将字节读入内存MemoryStream:

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

我还尝试了以下变体:

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)

使用此方法:

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

结论:

我觉得还有问题,希望你能回答这个问题。

Edit:

前端代码示例:

<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" />
}

控制器/操作示例:

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

我认为你的问题是你正在获取一个发布到你的控制器的base64字符串,将其视为ASCII,然后再次将其转换为base64。

我认为你需要改变这一行

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

to

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

从那里你的字节应该是正确的,你应该能够创建你的图像

--Edit--

我获取了您在文本文档中提供的示例数据,并在将其加载到位图中之前对其进行了解析。我能够将图像保存到我的硬盘上,并受到斯巴达人的欢迎(Go Green!!)

尝试一下这段代码,看看会发生什么。

请注意 imageData 正是公开的http://kristianbak.com/test_image.txt http://kristianbak.com/test_image.txt。我本来会提供初始化,但它是一个相当大的字符串,可能会破坏东西。

string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
using ( var imageStream = new MemoryStream( imageBytes, false ) )
{
   Bitmap image = new Bitmap( imageStream );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# - 无论我尝试什么,Base64 字节数组到图像都会失败 的相关文章

  • 使用内部构造函数实例化类

    我有一个类 其构造函数被定义为内部 这意味着我无法实例化它 虽然这可能有道理 但出于调试和研究目的 我仍然愿意做一次 是否可以通过反射来做到这一点 我知道我可以访问私有 内部成员 但是我可以调用内部构造函数吗 或者 由于构造函数没有做任何重
  • boost::interprocess 准备好迎接黄金时间了吗? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我正在开发一个由内存映射文件支持的线
  • 在两个 .cpp 文件之间定义全局变量 [重复]

    这个问题在这里已经有答案了 如何在 A cpp 和 B cpp 之间共享 全球化 bool 变量 其中它们都不包含其他 h 文件 他们有其他联合头文件 但彼此没有 我可以在这些共享标头中定义全局变量吗 Thanks 我可以在这些共享标头中定
  • C++ 有像 Pascal 一样的“with”关键字吗?

    withPascal 中的关键字可用于快速访问记录的字段 有人知道 C 是否有类似的东西吗 前任 我有一个包含许多字段的指针 但我不想这样输入 if pointer gt field1 pointer gt field2 pointer g
  • 何时对向量进行归一化?

    我正在学习 XNA 并且在几乎所有的教育套件中都可以找到http creators xna com en US http creators xna com en US 我总是看到向量上对 Normalize 的调用 我知道归一化基本上将向量
  • 可选参数“必须是编译时常量”

    我有一个类分为两个部分文件 如下所示 public partial class PersonRepository BaseRepository
  • 为什么 LinkedList 通常比 List 慢?

    我开始在我的一些 C 算法中使用一些 LinkedList 而不是列表 希望能够加快速度 然而 我注意到他们只是感觉更慢 像任何优秀的开发人员一样 我认为我应该尽职调查并验证我的感受 所以我决定对一些简单的循环进行基准测试 我认为用一些随机
  • C++:获取注册表值仅给出第一个字符[重复]

    这个问题在这里已经有答案了 我试图从注册表中获取字符串值 但我只得到第一个字母 HKEY hKey char gamePath MAX PATH if RegOpenKeyEx HKEY CURRENT USER L Software Bl
  • 如何在 C++ 的子目录中创建文件?

    这是我的代码 如何在子目录联系人中创建文件 每次创建该文件时 它都会出现在与我的程序相同的目录中 int main ofstream myfile contacts myfile open a myfile close 在构造函数中指定完整
  • CMake 警告:无法为目标生成安全的链接器搜索路径

    在为 pcl 项目运行 CMake 时 我收到一条警告消息 Configuring done CMake Warning at CMakeLists txt 12 add executable Cannot generate a safe
  • Windows 程序如何临时更改其时区?

    我写了一个函数来返回time t与给定日期的午夜相对应的值 当给定日期没有午夜时 它返回最早可用的时间 例如 当埃及进入夏令时时 这种情况就可能发生 今年 时间更改于 4 月 29 日晚上午夜生效 因此时钟直接从 23 59 转到 01 0
  • 首先EntityFramework数据库 - 类型映射 - 将binary(8)从SQL映射到C#中的int

    在 SQL 内部 我有一个主键为二进制 8 的表 当我使用该表添加到我的模型中时Update Model from Database我可以看到该列有 type Binary 在 C 中 我将该列设为byte 我可以将该列映射到 int 吗
  • IClaimsTransformation 未触发

    我尝试过实施一个IClaimsTransformation我在 ASP NET CORE 3 1 Web 应用程序中找到的类 public class ClaimsTransformer IClaimsTransformation publ
  • ASP MVC 5 - 403 customError 不起作用

    我正在尝试为我的应用程序创建自定义错误页面 它在大部分情况下都有效 但不适用于403 errors 我的网络配置
  • 基于 C++ 范围的 for 循环

    尝试使用基于范围的 for 循环执行某些操作 可以使用常规的 for 循环来完成 如下所示 vector
  • 使用对象列表构建树

    我有一个带有属性 id 和parent id 的对象列表 我想建造一棵树来连接那些孩子和父母 1 个父对象可以有多个子对象 并且有一个对象将成为所有对象的祖先 实现该功能最快的算法是什么 我使用 C 作为编程语言 但其他语言也可以 像这样的
  • 使 C# 编译器相信执行将在成员返回后停止

    我认为目前这是不可能的 或者这是否是一个好主意 但这是我刚才正在考虑的事情 我使用 MSTest 对我的 C 项目进行单元测试 在我的一项测试中 我执行以下操作 MyClass instance try instance getValue
  • printf 参数不足

    我的问题是关于缺少参数的 printf 之后的行为 printf s blah blah d int integer was given as argument and not int written 我已经知道 如果格式参数不足 则行为是
  • 统一;随机物体移动[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我正在制作一款机器人战斗游戏 我希望敌人随机移动 然后有时会向敌人移动 我希望运动包含在其中的代码 else if avoid fal
  • XmlDocument Save 使文件保持打开状态

    我有一个简单的 C 函数 可以创建一个基本的 XML 文件并保存 private void CreateXMlFile string Filename string Name string Company XmlDocument doc n

随机推荐