0

I need to programmatically assign form's wallpaper by a jpg file choosed by user. I've do this with new Bitmap but jpeg file become read only if I do so.

It's possibile to load in RAM jpeg file and use it for wallpaper? Or add jpeg file to project resource and use resource?

Sorry for my very very bad English :(

Best regards.

user1849976
  • 53
  • 1
  • 10

2 Answers2

2

Use a MemoryStream:

MemoryStream ms = new MemoryStream(File.ReadAllBytes(pathToImageFile));
this.BackgroundImage = Image.FromStream(ms); ;
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
0

The simplest way to avoid the file lock that GDI+ puts on the file is to make a deep copy of the bitmap with the Bitmap(Image) constructor. Like this:

    private void SetWallpaperButton_Click(object sender, EventArgs e) {
        if (openFileDialog1.ShowDialog() == DialogResult.OK) {
            using (var img = Image.FromFile(openFileDialog1.FileName)) {
                if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
                this.BackgroundImage = new Bitmap(img);
            }
        }
    }

The using statement ensures that the file lock gets released. And the Dispose() call ensures that the old bitmap gets destroyed quickly, important because you are often skirting OOM with large bitmaps on a 32-bit operating system.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Difference beetwen this and previous method? – user1849976 Feb 09 '13 at 16:03
  • Two big ones. First the bitmap is guaranteed to be compatible with the video adapter's pixel format so it will render quickly. Secondly it is much easier to dispose the unmanaged resources. When you use a MemoryStream then you have to keep it around until the bitmap is no longer in use. – Hans Passant Apr 14 '13 at 14:46