【问题标题】:Prevent image from being blocked for overwrite since it is dynamically loaded as background防止图像被阻止覆盖,因为它是作为背景动态加载的
【发布时间】:2012-09-09 05:17:49
【问题描述】:

编辑:另见我关于这个程序的旧帖子以获取背景信息C# - Making a BackgroundImage update in real time while editing it in other programs

我创建了一个图像查看器,它将所选图像显示为“表单”的背景。

在我关闭程序之前,我加载的所有图像都不会被其他应用程序覆盖,例如 Photoshop 或 GIMP 等图像处理应用程序。

我的代码很简单:

public partial class Form1:Form {
    private string FileName;

    public Form1() {
        InitializeComponent();

        FileName = "";
        openFileDialog1.Filter = "PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg";
    }

    private void button1_Click( object sender, EventArgs e ) {
        if(openFileDialog1.ShowDialog() == DialogResult.OK) {
            button2.Enabled = true;
            FileName = openFileDialog1.FileName;
            setImage();
        }
    }

    private void button2_Click( object sender, EventArgs e ) {
        setImage();
    }

    private void setImage() {
        Stream str=new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        Bitmap tempImg= new Bitmap( Bitmap.FromStream(str) );
        str.Close();
        using( tempImg = new Bitmap(FileName) ) {
            Rectangle rect = new Rectangle(0, 0, tempImg.Width, tempImg.Height);
            PixelFormat format = tempImg.PixelFormat;

            this.BackgroundImage = new Bitmap(FileName).Clone(rect, format);
        }
        openFileDialog1.FileName = "";
    }
}

我该如何解决这个问题?

更新:

此代码对我不起作用。

    private void setImage() {
        // using (FileStream stream = new FileStream("MyImage.png", FileMode.Open, FileAccess.Read))
        //var image = Image.FromStream(stream); 
        using( new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read) ) {
            Stream str=new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            Bitmap tempImg= new Bitmap( Bitmap.FromStream(str) );
            str.Close();
            tempImg = new Bitmap(FileName);
            Rectangle rect = new Rectangle(0, 0, tempImg.Width, tempImg.Height);
            PixelFormat format = tempImg.PixelFormat;

            this.BackgroundImage = new Bitmap(FileName).Clone(rect, format);
        }
        openFileDialog1.FileName = "";
    }

【问题讨论】:

  • 在你的setImage 中你有两次str.Close()...
  • 我的错,我刚刚在发布时添加了它。 ^^
  • 除了你创建Bitmap 3 次!!!你这样做是为了什么?
  • 这个代码是在我的上一个建议中给我的。发布 -> stackoverflow.com/questions/12375294/…
  • 我想你应该按照这个答案。它可以满足您的需要。只需将该答案与您在此问题中发布的代码进行比较即可。

标签: c# image background overwrite blocked


【解决方案1】:
using (FileStream stream = new FileStream("MyImage.png", FileMode.Open, FileAccess.Read))
{
   var image = Image.FromStream(stream);

    // Do something with the image.
}

// The image will not be locked here.

【讨论】:

  • 我刚刚试了一下,运行该代码并在退出使用 {} 后打开了paint.net,我能够编辑图像。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
相关资源
最近更新 更多