2016-09-16 5 views
-1

Привет, эксперты. Я получаю изображения в картинке из двух выпадающих списков comboboxes (скажем, 15-20 изображений), выбирая конкретные папки. Я хочу отрегулировать их яркость, поэтому, когда i переместите трек-панель, чтобы отрегулировать яркость, окно вывода исчезает и отображает сообщение об ошибке. Я работаю с VS2013-winforms с C#. Заранее спасибо, я попытался с,Получение неожиданного исключения при использовании моего трекбара для настройки яркости-C#

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     Bitmap newbitmap; 

     ArrayList alist = new ArrayList(); 
     int i = 0; 
     int filelength = 0;  

     public Form1() 
     { 
      InitializeComponent(); 
     }                    

     private void Form1_Load(object sender, EventArgs e) 
     { 
      DirectoryInfo di = new DirectoryInfo(@"C:\Users\Arun\Desktop\scanned"); 
      DirectoryInfo[] folders = di.GetDirectories(); 
      comboBox1.DataSource = folders; 
     } 

     private void button7_Click(object sender, EventArgs e) 
     { 
      if (i + 1 < filelength) 
      { 
       pictureBox1.Image = Image.FromFile(alist[i + 1].ToString()); 
       i = i + 1; 
       pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 
      } 
     } 

     private void button8_Click(object sender, EventArgs e) 
     { 

      if (i - 1 >= 0) 
      { 

       pictureBox1.Image = Image.FromFile(alist[i - 1].ToString()); 
       pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 
       i = i - 1; 
      } 
     } 

     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      string selected = comboBox1.SelectedItem.ToString(); 
      String fullpath = Path.Combine(@"C:\Users\Arun\Desktop\scanned", selected); 
      DirectoryInfo di1 = new DirectoryInfo(fullpath); 
      DirectoryInfo[] folders1 = di1.GetDirectories(); 
      comboBox2.DataSource = folders1; 

     } 

     private void button9_Click(object sender, EventArgs e) 
     { 


      string selected1 = comboBox1.SelectedItem.ToString(); 
      string selected2 = comboBox2.SelectedItem.ToString(); 

         //Initially load all your image files into the array list when form load first time 
      System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(Path.Combine(@"C:\Users\Arun\Desktop\scanned", selected1, selected2)); //Source image folder path 


      try 
      { 


       if ((inputDir.Exists)) 
       { 
        alist.Clear(); 
        //Get Each files 
        System.IO.FileInfo file = null; 
        foreach (System.IO.FileInfo eachfile in inputDir.GetFiles()) 
        { 
         file = eachfile; 
         if (file.Extension == ".tif") 
         { 
          alist.Add(file.FullName); //Add it in array list 
          //filelength = filelength + 1; 
          filelength = alist.Count; 
         } 
         else if(file.Extension == ".jpg") 
         { 

          alist.Add(file.FullName); //Add it in array list 
          // filelength = filelength + 1; 
          filelength = alist.Count; 
         } 
        } 

        pictureBox1.Image = Image.FromFile(alist[0].ToString()); //Display intially first image in picture box as sero index file path 
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 
        i = 0; 

       } 
      } 
      catch (Exception ex) 
      { 

      } 

     }                   

     private void trackBar1_Scroll(object sender, EventArgs e) 
     { 


      label2.Text = trackBar1.Value.ToString(); 
      pictureBox1.Image = adjustbrightness (newbitmap, trackBar1.Value); 
     } 

     public static Bitmap adjustbrightness(Bitmap image,int value) 
     { 
      Bitmap tempbitmap = image; 

      float finalvalue = (float)value/255.0f; 

      Bitmap newbitmap = new Bitmap(tempbitmap.Width, tempbitmap.Height); 

      Graphics newgraphics = Graphics.FromImage(newbitmap); 

      float[][] floatcolormatrix = { 
              new float[] {1,0,0,0,0}, 
              new float[] {0,1,0,0,0}, 
              new float[] {0,0,1,0,0}, 
              new float[] {0,0,0,1,0}, 
              new float[] {finalvalue,finalvalue,finalvalue,1,1} 
             }; 
      ColorMatrix newcolormatrix = new ColorMatrix(floatcolormatrix); 

      ImageAttributes attributes = new ImageAttributes(); 

      attributes.SetColorMatrix(newcolormatrix); 

      newgraphics.DrawImage(tempbitmap, new Rectangle(0, 0, tempbitmap.Width, tempbitmap.Height), 0, 0, tempbitmap.Width, tempbitmap.Height, GraphicsUnit.Pixel, attributes); 

      attributes.Dispose(); 

      newgraphics.Dispose(); 

      return newbitmap; 


     } 

    } 
} 
+0

Можете ли вы предоставить конкретную ошибку? Как и трассировка стека, если она у вас есть? – Thumper

+0

Сообщение об ошибке, вероятно, «IndexOutOfBoundsException»? –

+0

Необработанное исключение типа «System.NullReferenceException» произошло в WindowsFormsApplication1.exe Дополнительная информация: Ссылка на объект не установлена ​​в экземпляр объекта. @Thumper – warriors

ответ

0

Вы перепутали поле и локальную переменную:

поле под Bitmap newbitmap никогда не будет назначен.

pictureBox1.Image = adjustbrightness (newbitmap, trackBar1.Value); 

Метод adjustbrightness будет врезаться на получении доступа к свойствам здесь:

public static Bitmap adjustbrightness(Bitmap image,int value) 
    { 
     Bitmap tempbitmap = image; 

     float finalvalue = (float)value/255.0f; // <- this should probably be 256.0f 

     Bitmap newbitmap = new Bitmap(tempbitmap.Width, tempbitmap.Height); // <------- 

     Graphics newgraphics = Graphics.FromImage(newbitmap); 

Параметр image, который передается, никогда не назначается.

Чтобы исправить это, вы не должны загружать растровое изображение непосредственно в окно изображения. (pictureBox1.Image = Image.FromFile(alist[0].ToString());) Но всегда с помощью метода adjustbrightness:

pictureBox1.Image = adjustbrightness(Image.FromFile(alist[0].ToString()), 255);

И удалить поле Bitmap newbitmap;

+0

Это не работает, не вносит никаких изменений @Jeroen van Langen – warriors

+0

Используйте отладчик и проверяйте, где объект «null» –