convert byte[] to image

前端 未结 1 431
小鲜肉
小鲜肉 2021-01-24 11:04

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

There was an error - Argument Exception was unhandled by user code

相关标签:
1条回答
  • 2021-01-24 12:00

    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:

    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";
    }
    
    0 讨论(0)
提交回复
热议问题