C# 将字节 [] 转换为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14360257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:35:41  来源:igfitidea点击:

convert byte[] to image

c#type-conversionbyte

提问by sihao

I have uploaded an Image in to my database as byte[]and now im trying to display it out.

我已将图像上传到我的数据库中byte[],现在我正在尝试将其显示出来。

There was an error - Argument Exception was unhandled by user code Parameter is not valid

出现错误 - 用户代码未处理参数异常 Parameter is not valid

At this line

在这一行

newImage = System.Drawing.Image.FromStream(stream);

Here is my codes

这是我的代码

for (int i = 0; i < topRatingList.Count; i++)
            {
                int commentRating = topRatingList[i].CommentRating;
                int drinkID = topRatingList[i].DrinkID;

                if (i == 0)
                {
                    DrinkMenuDAO drink = DrinkMenuBLL.getDrinkMenu(drinkID);
                    LinkButton1.Text = drink.DrinkName; 
                    ImageButton1.ImageUrl = byteArrayToImage(drink.DrinkImage);
                }
            }


private string byteArrayToImage(byte[] byteArrayIn)
    {
        System.Drawing.Image newImage;
        string strFileName = Server.MapPath("~/Temp/images/") + ".jpg";
        if (byteArrayIn != null)
        {
            using (MemoryStream stream = new MemoryStream(byteArrayIn))
            {
                newImage = System.Drawing.Image.FromStream(stream);
                newImage.Save(strFileName);
            }
            return strFileName;
        }
        else
        {
            return "";
        }
    }


the code that i used to store the image

我用来存储图像的代码

protected void bn_upload_Click(object sender, EventArgs e)
    {
        lbl_msg.Text = "";
        Stream imgStream = FileUpload1.PostedFile.InputStream;
        BinaryReader imgBinary = new BinaryReader(imgStream);
        bytes = imgBinary.ReadBytes((Int32)imgStream.Length);
        imgBinary.Close();
        imgStream.Close();
        string src = byteArrayToImage(bytes);
        if (src.Equals(""))
        {
        }
        else
        {
            Image1.ImageUrl = "~/Temp/UploadedImage.jpg";
        }
    }

    private string byteArrayToImage(byte[] byteArrayIn)
    {
        System.Drawing.Image newImage;
        string strFileName = Server.MapPath("~/Temp/") + "UploadedImage.jpg";
        if (byteArrayIn != null)
        {
            using (MemoryStream stream = new MemoryStream(byteArrayIn))
            {
                newImage = System.Drawing.Image.FromStream(stream);
                newImage.Save(strFileName);
            }
            return strFileName;
        }
        else
        {
            return "";
        }
    }

    protected void btn_submit_Click(object sender, EventArgs e)
    {
        DrinkMenuBLL.uploadImg(bytes);
        lbl_msg.Text = "uploaded";
    }

I used varbinary(MAX)in the database and the sql that i used

varbinary(MAX)在数据库和我使用的sql中使用过

public static void UploadImg(byte[] drinkImage)
    {

        SqlConnection con = new SqlConnection(Constring.getConString());

        string sql = "Update DrinkMenu set drinkImage = (@imgData) where drinkID = 4";

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add("@imgData", SqlDbType.Binary).Value = drinkImage;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        finally
        {
            con.Close();
            cmd.Dispose();
            con.Dispose();
        }
    }

回答by Tommaso Belluzzo

One problem could be the following one:

一个问题可能是以下问题:

bytes = imgBinary.ReadBytes((Int32)imgStream.Length);

What if the stream Length is more than Int32.MaxValue as it's a Int64? Maybe you are truncating your image... use this method instead to read the stream to a buffer:

如果流长度超过 Int32.MaxValue 因为它是 Int64 怎么办?也许您正在截断您的图像...使用此方法将流读取到缓冲区:

public static Byte[] ReadStream(Stream input)
{
    Byte[] buffer = new Byte[(16 * 1024)];

    using (MemoryStream stream = new MemoryStream())
    {
        Int32 read;

        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            stream.Write(buffer, 0, read);

        return stream.ToArray();
    }
}

protected void bn_upload_Click(object sender, EventArgs e)
{
    lbl_msg.Text = "";

    Byte[] bytes = ReadStream(FileUpload1.PostedFile.InputStream);
    String src = byteArrayToImage(bytes);

    if (!src.Equals(""))
        Image1.ImageUrl = "~/Temp/UploadedImage.jpg";
}