Error“ Parameter is not valid ” while converting Bytes into Image

前端 未结 6 764
心在旅途
心在旅途 2020-11-30 12:19

I am converting bytes into an image but I get an error

Parameter is not valid

I am pasting my code. Kindly check the code and

相关标签:
6条回答
  • 2020-11-30 12:53

    After trying many things I found a way which has a little bit more control. In this example you can specify the pixel format and copy the bytes to a Bitmap.

    byte[] buffer = GetImageBytes();
    var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
    var bitmap_data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
    Marshal.Copy(buffer, 0, bitmap_data.Scan0, buffer.Length);
    bitmap.UnlockBits(bitmap_data);
    var result = bitmap as Image;
    
    0 讨论(0)
  • 2020-11-30 13:02

    The problem is because, you are bringing it incorrectly from database. Try changing your code like this:

    while (registry.Read())
    {
       byte[] image = (byte[])registry["Image"];
    }
    
    0 讨论(0)
  • 2020-11-30 13:02

    In my case I got the error since my base64 string had wrong encoding before calling Image.FromStream. This worked for me in the end:

    byte[] bytes = System.Convert.FromBase64String(base64ImageString);
    
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        var image = Image.FromStream(ms);
        image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
    }
    
    0 讨论(0)
  • 2020-11-30 13:06

    try this

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
        Image img = (Image)converter.ConvertFrom(byteArrayIn);
    
        return img;
    }
    
    0 讨论(0)
  • 2020-11-30 13:07
    cmd.CommandText="SELECT * FROM `form_backimg` WHERE ACTIVE=1";
    
    MySqlDataReader reader6= cmd.ExecuteReader();
    
    if(reader6.Read())
    {
       code4 = (byte[])reader6["BACK_IMG"];   //BLOB FIELD NAME BACK_IMG
    }
    reader6.Close();
    
    MemoryStream stream = new MemoryStream(code4);   //code4 is a public byte[] defined on top                             
    pictureBox3.Image = Image.FromStream(stream);
    
    0 讨论(0)
  • 2020-11-30 13:12

    try this,

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
         Image returnImage = null;
         using (MemoryStream ms = new MemoryStream(byteArrayIn))    
         {   
             returnImage = Image.FromStream(ms);     
         }
         return returnImage;
    }
    
    0 讨论(0)
提交回复
热议问题