Converting a JPEG image to a byte array - COM exception

后端 未结 4 2011
孤城傲影
孤城傲影 2020-12-29 23:47

Using C#, I\'m trying to load a JPEG file from disk and convert it to a byte array. So far, I have this code:

static void Main(string[] args)
{
    System.Wi         


        
相关标签:
4条回答
  • 2020-12-29 23:56

    Check the examples from this article: http://www.codeproject.com/KB/recipes/ImageConverter.aspx

    Also it's better to use classes from System.Drawing

    Image img = Image.FromFile(@"C:\Lenna.jpg");
    byte[] arr;
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        arr =  ms.ToArray();
    }
    
    0 讨论(0)
  • 2020-12-29 23:58

    The reason this error happens is because the BitmapFrame.Create() method you are using defaults to an OnDemand load. The BitmapFrame doesn't try to read the stream it's associated with until the call to encoder.Save, by which point the stream is already disposed.

    You could either wrap the entire function in the using {} block, or use an alternative BitmapFrame.Create(), such as:

    BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    
    0 讨论(0)
  • 2020-12-30 00:09
    public byte[] imageToByteArray(System.Drawing.Image imageIn)  
    {   
     MemoryStream ms = new MemoryStream();     
    
     imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);   
     return  ms.ToArray();   
    }
    
    0 讨论(0)
  • 2020-12-30 00:16

    Other suggestion:

    byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
    

    Should be working not only with images.

    0 讨论(0)
提交回复
热议问题