我搜索了整个堆栈溢出,但我找不到以下答案:
当我使用我的OpenFileDialog时 ,我打开的文件被阻止用于我的程序,直到我关闭程序。 所以如果我打开一个图像,我不允许在Windows资源管理器中替换该图像。
我认为这是处置我的OpenFileDialog的问题,但我不知道如何解决它...
我的代码:
using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Title = "Open Image"; ofd.Filter = "PNG Image(*.png|*.png" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|JPEG Compressed Image (*.jpg|*.jpg"; if (ofd.ShowDialog() == DialogResult.OK) { pictureBox1.Image = new Bitmap(ofd.FileName); } }我认为using块可以解决这个问题,但是不会...它仍然被程序使用。 我想在picturebox中加载图像,然后我希望图像再次可用(所以我可以重命名它,替换它等)。
I have searched throughout entire Stack Overflow, but I couldn't find an answer to the following:
When I'm using my OpenFileDialog, the files I open get blocked for use out of my program until I close my program. So if I open an image, I am not allowed to replace that image in my Windows Explorer anymore.
I think this is a problem with disposing my OpenFileDialog, but I'm not sure how to solve it...
My code:
using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Title = "Open Image"; ofd.Filter = "PNG Image(*.png|*.png" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|JPEG Compressed Image (*.jpg|*.jpg"; if (ofd.ShowDialog() == DialogResult.OK) { pictureBox1.Image = new Bitmap(ofd.FileName); } }I thought that the using block would solve this problem, but nope... It still gets used by the program. I want to load the image in the picturebox and then I want the image to be available again (so I can rename it, replace it, etc...).
最满意答案
如Chris所写,请尝试如下所示:
pictureBox1.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(old.FileName)));它使用File.ReadAllBytes读取所有文件,将其放入MemoryStream并将MemoryStream传递给Image静态初始化程序。
相当于:
byte[] bytes = File.ReadAllBytes(old.FileName); MemoryStream ms = new MemoryStream(bytes); pictureBox1.Image = Image.FromStream(ms);你不能丢弃MemoryStream ! 如果/当Image将被丢弃时, MemoryStream的终结器将会启动(如果您没有其他ms引用)并且将丢弃MemoryStream (请注意,这不会立即发生......)当GC运行时会发生一些事情)
As written by Chris, try something like:
pictureBox1.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(old.FileName)));It reads all the file with File.ReadAllBytes, put it in a MemoryStream and pass the MemoryStream to the Image static initializer.
Equivalent to:
byte[] bytes = File.ReadAllBytes(old.FileName); MemoryStream ms = new MemoryStream(bytes); pictureBox1.Image = Image.FromStream(ms);You mustn't dispose the MemoryStream! If/when the Image will be disposed, the finalizer of MemoryStream will kick in (if you don't have other references to ms) and the MemoryStream will be disposed (note that this isn't something that will happen immediately... It's something that will happen when the GC will run)
更多推荐
发布评论