c# - 图像变量到 byte[] 数组

标签 c# image winforms arrays

我遇到了一个我认为很容易解决的问题,只是我做错了一些事情,所以: 我有一个 Android 平板电脑,用户可以在其中绘制签名,我通过 adb 获取图像(.JPEG)。

    ProcessStartInfo adb_copy = new ProcessStartInfo("C:/SCR/adb/adb.exe");
    adb_copy.Arguments = "pull \"mnt/sdcard/sign.jpg\" \"C:\\SCR\\temp\\sign.jpg\"";
    adb_copy.WindowStyle = ProcessWindowStyle.Hidden;
    Process.Start(adb_copy);

我有两个Image变量:

Image WORKER_sign;
Image EMPLOYER_sign;

我将图像加载到这些中,也加载到图片框中:

    using (FileStream stream = new FileStream("C:/SCR/temp/sign.jpg", FileMode.Open, FileAccess.Read))
    {
        WORKER_sign = Image.FromStream(stream);
        stream.Close();
    }
    pictureBox3.Image = WORKER_sign;
    pictureBox3.SizeMode = PictureBoxSizeMode.Zoom;

图片框完美地显示了图像,但是我无法写入字节数组。我尝试了以下代码:

public static byte[] ImageToByte(Image img)
{
    if (img == null) return null;
    byte[] result;
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, img.RawFormat);
        result = stream.GetBuffer();
    }
    return result;
}
byte[] temparray = ImageToByte(WORKER_SIGN);

但是最后一行向我抛出了一个通用 GDI+ 异常,在此之前 IntelliTrace 也显示了一些 System.ObjectDisposeException(“已关闭文件”)。

我的代码有什么问题吗? 感谢您的所有帮助! :)

关闭:抱歉我的英语不好...

编辑:错误:

Exception:Thrown: "Cannot access a closed Stream." (System.ObjectDisposedException) A System.ObjectDisposedException was thrown: "Cannot access a closed Stream." Time: 2014.08.11. 14:37:49 Thread:Main Thread[7276]

Exception:Thrown: "Generic error in: GDI+." (System.Runtime.InteropServices.ExternalException) A System.Runtime.InteropServices.ExternalException was thrown: "Generic error in: GDI+." Time: 2014.08.11. 14:37:49 Thread:Main Thread[7276]

最佳答案

将代码更改为:

public static byte[] ImageToByte(Image img)
{
    if (img == null) return null;
    byte[] result;
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, img.RawFormat);
        result = stream.ToArray();
    }
    return result;
}

关于c# - 图像变量到 byte[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25243431/

相关文章:

c# - "No value given for one or more required parameters"访问Excel电子表格

.net - 如何找出线程锁发生的位置?

c# - 在后台工作程序中向 GUI 添加控件

c# - 在每次调用时重新评估常量 FieldExpression 的值

java - 如何随着窗口大小的调整而调整 JLabel 中图像的大小?如何保持适当的规模?

c++ - 在 C++ 中读取/操作图像

javascript - 在代码中发布引用图像

c# - 如何在使用过滤器时获取 CollectionView 的真实计数?

c# - 文本 block 绑定(bind)不会在运行时更新

c# - C#有解析多层级联JSON的库吗?