C#加载JPG文件,提取BitmapImage

15

我想从JPG中提取一个BitmapImage。这是我的代码:

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();

图片返回的是一个0×0的图像,这当然意味着它没有起作用。我该怎么做?

1个回答

26

试试这个:

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
    }
}

或者你可以这样做(来源):

Bitmap myBmp = Bitmap.FromFile("path here");

我发现了我的错误:我需要使用Image而不是BitmapImage。我知道它不需要太复杂!这是可行的代码:Image image = Image.FromFile(sourceFileName, true); - IamIC
2
这一开始真是复杂!Image、BitmapImage、ImageSource、JpegImageDecoder等等。 - IamIC
7
这是我们的工作稳定性,嘿嘿嘿 :) - Eugene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接