[英]Prevent image from being blocked for overwrite since it is dynamically loaded as background
EDIT: also see my older post about this programm to get background informations C# - Making a BackgroundImage update in real time while editing it in other programs 编辑:也请参阅我有关此程序的较早的帖子以获取背景信息C#-在其他程序中编辑它时实时更新BackgroundImage
I've created an image viewer, it displays a chosen image as the background of a 'Form'. 我创建了一个图像查看器,它显示一个选定的图像作为“表单”的背景。
Until I close the program, all images I've loaded in, are blocked from being overwritten with other applications, such as image manipulating apps like Photoshop or GIMP. 在我关闭程序之前,已加载的所有图像均被其他应用程序(如Photoshop或GIMP等图像处理应用程序)覆盖。
My code is pretty simple : 我的代码很简单:
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 = "";
}
}
How can I solve this problem ? 我怎么解决这个问题 ?
UPDATE : 更新:
This code doesn't work for me. 此代码对我不起作用。
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 = "";
}
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.