位图转换 [英] Bitmap Conversion

查看:74
本文介绍了位图转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将网络摄像头从客户端流传输到服务器,但是在从字节数组转换回服务器上的位图时遇到困难。

I'm trying to stream a webcam across from a client to a server but I'm having difficulty at the conversion from the byte array back to the bitmap on the server.

这是代码:

public void handlerThread()
{
    Socket handlerSocket = (Socket)alSockets[alSockets.Count-1];
    NetworkStream networkStream = new
    NetworkStream(handlerSocket);
    int thisRead=0;
    int blockSize=1024;
    Byte[] dataByte = new Byte[blockSize];
    lock(this)
    {
        // Only one process can access
        // the same file at any given time
        while(true)
        {
            thisRead=networkStream.Read(dataByte,0,blockSize);

            pictureBox1.Image = byteArrayToImage(dataByte);
            if (thisRead==0) break;
        }
        fileStream.Close();
    }
    lbConnections.Items.Add("File Written");
    handlerSocket = null;
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);  //here is my error
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

在上面标记的点上,尝试输入参数无效转换回图像并崩溃。关于我在做什么错的任何建议?

At the point marked above I get "Parameter is not valid" when trying to convert back to the image and crash. Any suggestions as to what I'm doing wrong?

推荐答案

请注意:
Image.Save(..)抛出GDI +异常,因为内存流已关闭

您可以创建扩展方法,也可以删除传统方法的 this。这看起来与您的代码相同,所以我想知道您是否存在某种编码类型或其他与创建基础字节数组有关的问题?

You can create an extension method or remove the "this" for a traditional method. This looks the same as your code so I wonder if you have some type of encoding or other issue relatd to creating your underlying byte array?

public static Image ToImage(this byte[] bytes)
{
    // You must keep the stream open for the lifetime of the Image.
    // Image disposal does clean up the stream.

    var stream = new MemoryStream(bytes);
    return Image.FromStream(stream);
}

这篇关于位图转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆