I have a small image editing program that opens an image and does fancy stuff to it. In this case, I'm trying to adjust the brightness of the pixels. The problem isn't getting the pixels right, its disposing the Bitmap/BitmapSources being created in the ValueChanged event for my slider.
So basically the user will click a button and it will open up a new window with a slider. This new window makes a copy of the original bitmap for later use.
When the slider's value changes, it will create a new Bitmap from the original with the corresponding brightness increase, create a new BitmapSource from this, and update the image control's source. Even though I'm using a 'using' statement, I still get an "out of memory" exception after sliding for so long.
Any idea why this is? Is there a better workaround that can achieve the same thing? I have included the code below:
using Imagin.Slideshow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Imagin
{
/// <summary>
/// Interaction logic for BrightnessWindow.xaml
/// </summary>
public partial class BrightnessWindow : Window
{
public int Increase;
private System.Drawing.Bitmap Bitmap;
private System.Drawing.Bitmap NewBitmap;
private MainWindow ParentWindow;
public BrightnessWindow(MainWindow m)
{
InitializeComponent();
this.ParentWindow = m;
this.Bitmap = (System.Drawing.Bitmap)this.ParentWindow.Document.Bitmap.Clone();
}
private void slider1_ValueChanged(object sender, RoutedEventArgs e)
{
using (System.Drawing.Bitmap b = (System.Drawing.Bitmap)this.ParentWindow.Document.Bitmap.Clone(new RectangleF() { Width = (int)this.ParentWindow.Document.Bitmap.Width, Height = (int)this.ParentWindow.Document.Bitmap.Height, X = 0, Y = 0 }, this.ParentWindow.Document.Bitmap.PixelFormat))
{
this.ParentWindow.SetPixels(b, AdjustmentTypes.Brightness, Convert.ToInt32(this.slider1.Value));
BitmapSource m = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
this.ParentWindow.image1.Source = m;
this.NewBitmap = (System.Drawing.Bitmap)b.Clone();
}
}
private void applyButton_Click(object sender, RoutedEventArgs e)
{
if (this.NewBitmap != null)
{
this.ParentWindow.Document.Bitmap = this.NewBitmap;
}
this.Close();
}
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
this.ParentWindow.Document.Refresh();
this.Close();
}
}
}
Another thing I was wondering is if there is a better way to alter the MainWindow's controls without having to pass it as a parameter, or is this the preferred approach for that kind of thing? Thanks!