C# Load JPG file, extract BitmapImage

48,586

Try this:

public void Load(string fileName) 
{

    using(Stream BitmapStream = System.IO.File.Open(fileName,System.IO.FileMode.Open ))
    {
         Image img = Image.FromStream(BitmapStream);

         mBitmap=new Bitmap(img);
         //...do whatever
    }
}

Or you can just do this (source):

Bitmap myBmp = Bitmap.FromFile("path here");
Share:
48,586
IamIC
Author by

IamIC

An artistic engineer & humanitarian at heart. As a technology architect, I create solutions which take the confusions out of things. I love to help people.

Updated on April 26, 2020

Comments

  • IamIC
    IamIC about 4 years

    I am trying to extract a BitmapImage from a JPG. This is the code I have:

    FileStream fIn = new FileStream(sourceFileName, FileMode.Open); // source JPG
    Bitmap dImg = new Bitmap(fIn);
    MemoryStream ms = new MemoryStream();
    dImg.Save(ms, ImageFormat.Jpeg);
    image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = new MemoryStream(ms.ToArray());
    image.EndInit();
    ms.Close();
    

    image comes back with a 0 × 0 image, which of course means it didn't work. How do I do this?

  • IamIC
    IamIC about 12 years
    I found my mistake: I need to use Image, not BitmapImage. I knew it didn't need to be complicated! This is the working code: Image image = Image.FromFile(sourceFileName, true);
  • IamIC
    IamIC about 12 years
    Boy is this complicated initially! Image, BitmapImage, ImageSource, JpegImageDecoder etc. etc.
  • Eugene
    Eugene about 12 years
    This is our job security, hehehe :)