Picturebox duplicating value - c#

I am working on a little program that starts taking pictures in the moment you click on a button. Also it can be ended earlier clicking another button.
The little bug that I am having is that I use a timer to process each time you go throw it since you hit the start button in a 1000ms interval, the problem comes when the first process finishes, the next process you start will duplicate the value of a progressbar x2 forever until you close the app.
namespace Fotos
{
public partial class Fotos : Form
{
private static string Path = #"C:\Fotos\";
//private static string Agua = #"C:\Marca de Agua\";
private bool HayDispositivos, terminado;
private string nombre;
private int i = 0, j = 0, z = 0, eleccion;
private FilterInfoCollection MisDispositivos;
private VideoCaptureDevice miWebcam;
private MagickImageCollection gif = new MagickImageCollection();
public Fotos()
{
InitializeComponent();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private void Creador()
{
CreacionGif cg = new CreacionGif(gif, nombre);
cg.ShowDialog();
}
private void MarcaAgua(PictureBox picturebox1)
{
RectangleF angulo = new RectangleF(1350, 975, 535, 90); //rectf for My Text
using (Graphics g = Graphics.FromImage(picturebox1.Image))
{
//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(DateTime.Now.ToString(), new Font("Tahoma", 32, FontStyle.Bold), Brushes.White, angulo, sf);
EncoderParameters myEncoderParameters = new EncoderParameters(1);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L);
myEncoderParameters.Param[0] = myEncoderParameter;
if (progressBar1.Value == 0)
{
j = 0;
}
picturebox1.Image.Save(Path + textBoxNombreFoto.Text + "_" + i + ".jpg", jpgEncoder, myEncoderParameters);
gif.Add(Path + textBoxNombreFoto.Text + "_" + i + ".jpg");
gif[j].AnimationDelay = 200;
j++;
g.Dispose();
sf.Dispose();
/* using (Image image = pictureBox1.Image)
using (Image watermarkImage = Image.FromFile(Agua +"fecha.jpg"))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (image.Width / 2 - watermarkImage.Width / 2);
int y = (image.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
image.Save(Path + i +".jpg");*/
}
}
private void Form_Load(object sender, EventArgs e)
{
CargaDispositivos();
}
public void CargaDispositivos()
{
MisDispositivos = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (MisDispositivos.Count > 0)
{
HayDispositivos = true;
for (int i = 0; i < MisDispositivos.Count; i++)
comboBox1.Items.Add(MisDispositivos[i].Name.ToString());
comboBox1.Text = MisDispositivos[0].Name.ToString();
}
else HayDispositivos = false;
}
private void CerrarWebcam()
{
if (miWebcam != null && miWebcam.IsRunning)
{
miWebcam.SignalToStop();
miWebcam = null;
}
}
private void Capturando(object sender, NewFrameEventArgs eventArgs)
{
if(terminado == false)
{
Bitmap Imagen = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = Imagen;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CerrarWebcam();
}
private void foto_Click(object sender, EventArgs e)
{
if (miWebcam != null && miWebcam.IsRunning && (radioButton1.Checked == true || radioButton2.Checked == true) && textBoxNombreFoto.TextLength > 0)
{
timer1.Enabled = true;
timer1.Start();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
terminado = false;
if(radioButton1.Checked == true)
{
eleccion = 18;
progressBar1.Maximum = 1800;
}
else
{
eleccion = 36;
progressBar1.Maximum = 3600;
}
}
else
{
MessageBox.Show("Por favor revisa que todos los campos estén rellenos");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
CerrarWebcam();
int i = comboBox1.SelectedIndex;
string nombreVideo = MisDispositivos[i].MonikerString;
miWebcam = new VideoCaptureDevice(nombreVideo);
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
miWebcam.Start();
}
private void finFoto_Click(object sender, EventArgs e)
{
MarcaAgua(pictureBox1);
terminado = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value % 30 == 0 && progressBar1.Value <= eleccion && terminado != true || progressBar1.Value == 0)
{
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
MarcaAgua(pictureBox1);
z++;
}
if (progressBar1.Value < eleccion && terminado != true)
{
progressBar1.Value++;
i++;
}
textBoxTiempo.Text = progressBar1.Value.ToString();
textBoxTiempo.Update();
if ((terminado == true || progressBar1.Value >= eleccion) && i!=0)
{
timer1.Stop();
timer1.Dispose();
progressBar1.Dispose();
progressBar1.Value = 0;
nombre = textBoxNombreFoto.Text;
Creador();
i = 0;
MessageBox.Show("Proceso Terminado con Éxito");
}
}

Related

Outputting Images on Form

I am creating a c# piano which when clicking on a music key, an image of the music note is outputted on the form, however no image is being outputted. I am sure that the image path for the bitmap images is correct so I am not sure whether I have done something wrong in the code or I need to add some events to the form itself.Can somebody help me with this please ?
This is the Form class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Threading;
namespace NewPiano
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SoundPlayer sp = new SoundPlayer();
int count;
private Control mn;
int xLoc = 50;
int yLoc = 30;
List<MusicNote> notes = new List<MusicNote>();
private void Form1_Load(object sender, System.EventArgs e)
{
MusKey mk;
BlackMusKey bmk;
int[] whitePitch = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24 };
int[] blackPitch = new int[] { 2, 4, 7, 9, 11, 14, 16, 19, 21, 23 };
int[] xPos = new int[] { 10, 30, 70, 90, 110, 150, 170, 210, 230, 250 };
for (int k = 0; k < 7; k++)
{
int iNote = whitePitch[k];
int xpos = k * 40;
mk = new MusKey(iNote, xpos + 225, 300);
mk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown);
mk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(mk);
}
int xOffs = 20;
for (int k = 0; k < 5; k++)
{
int iNote = blackPitch[k];
int xpos = xPos[k] * 2;
bmk = new BlackMusKey(iNote, xpos + 225, 300);
bmk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown);
bmk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(bmk);
this.panel1.Controls[this.panel1.Controls.Count - 1].BringToFront();
}
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.panel1.Controls.OfType<MusKey>())
{
if(sender == mk)
{
if(e.Button == MouseButtons.Left)
{
timer1.Enabled = true;
count = 0;
timer1.Start();
sp.SoundLocation = #"C:/Users/Kim/Desktop/Notes-Sound files/mapped/" + mk.musicNote + ".wav"; //change this to the location of your "mapped" folder
sp.Load();
sp.Play();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count ++;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.panel1.Controls.OfType<MusKey>())
{
if (sender == mk)
{
if (e.Button == MouseButtons.Left)
timer1.Enabled = false;
textBox1.Text = count.ToString();
sp.Stop();
string bNoteShape = null;
int duration = 0;
//Insert note lengths
if (count >= 16)
{
bNoteShape = "SemiBreve";
duration = (16 + 20) / 2;
}
else if ((count >= 11) && (count <= 15))
{
bNoteShape = "DotMin";
duration = (11 + 15) / 2; //average
}
else if ((count >= 6) && (count <= 10))
{
bNoteShape = "Minim";
duration = (6 + 10) / 2; //average
}
else if ((count >= 3) && (count <= 5))
{
bNoteShape = "Crotchet";
duration = (3 + 5) / 2; //average
}
else if ((count == 2))
{
bNoteShape = "Quaver";
duration = 2; //average
}
else if ((count >= 0) || (count <= 1))
{
bNoteShape = "SemiQuaver";
duration = 1;
}
//copied from handout
MusicNote mn = new MusicNote(mk.musicNote, duration, bNoteShape, xLoc);
notes.Add(mn);
mn.Location = new Point(xLoc, yLoc);
this.panel1.Controls.Add(this.mn);
xLoc = xLoc + 40;
}
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.panel1.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 1);
for (int k = 0; k < 5; k++)
{
int ypos = (k * 15) + 20;
graphicsObj.DrawLine(myPen, 20, ypos, 550, ypos);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (MusicNote mn in notes)
{
sp.SoundLocation = #"C:/Users/Kim/Desktop/Notes-Sound files/mapped/" + mn.pitch + ".wav"; //change this to the location of your "mapped" folder
sp.Play();
Thread.Sleep(mn.duration * 150);
}
}
}
}
This is the Music Note class:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NewPiano
{
public class MusicNote : PictureBox
{
Boolean isDragging = false;
public int pitch = 0;
public string noteshape = "";
public int duration = 0;
internal Point Location;
public int xLocation = 0;
public MusicNote(int notePitch, int duration, string bNoteShape, int xLoc) : base()
{
this.noteshape = bNoteShape;
this.duration = duration;
this.pitch = notePitch;
Location = new Point(xLoc, pitch);
this.Size = new Size(30, 30);
Bitmap bmp = new Bitmap(#"C:/Users/Kim/Desktop/Notes-Images/" + noteshape + ".bmp");
this.Image = bmp;
this.MouseDown += new MouseEventHandler(StartDrag);
this.MouseUp += new MouseEventHandler(StopDrag);
this.MouseMove += new MouseEventHandler(NoteDrag);
}
private void StartDrag(object sender, MouseEventArgs e) {
if(e.Button == MouseButtons.Left) {
isDragging = true;
pitch = e.Y;
this.Location = new Point(this.Location.X, pitch);
}
}
private void StopDrag(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = false;
pitch = e.Y;
}
}
private void NoteDrag(object sender, MouseEventArgs e)
{
if (isDragging)
{
this.Top = this.Top + (e.Y - this.pitch);
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
}

How can I find the start and end pixels cropped image?

I am a beginner programmer,I split an image into 16 parts (I'm making a picture puzzle game) And each one is inside a picturebox And randomly places them have
changed Now I want to know the beginning and end of each image I cut it connects to another image (I mean, any image Continue other). Is such a thing possible? Do you have a better idea?
namespace ImagePuzzelGame
{
public partial class Form1 : Form
{
Point move;
bool isDragging = false;
public Dictionary<int, Point> pics
{
set;
get;
}
private Point _defaultlocation = new Point(306, 306);
Random rnd = new Random();
public Point DefaultLocation
{
get
{
return _defaultlocation;
}
set
{
_defaultlocation = value;
}
}
public List<PictureBox> picPuzzle
{
get;
set;
}
public Bitmap newImage
{
get; set;
}
public Form1()
{
InitializeComponent();
pics = new Dictionary<int, Point>()
{
{1,new Point(0,0) },
{2,new Point(100,0) },
{3,new Point(200,0) },
{4,new Point(300,0) },
{5,new Point(400,0) },
{6,new Point(0,119) },
{7,new Point(100,119) },
{8,new Point(200,119) },
{9,new Point(300,119) },
{10,new Point(400,119) },
{11,new Point(0,325) },
{12,new Point(100,325) },
{13,new Point(200,325) },
{14,new Point(300,325) },
{15,new Point(400,325) },
};
List<PictureBox> picturebox = new List<PictureBox>
{
pictureBox1,pictureBox2,pictureBox3,pictureBox4,pictureBox5,pictureBox6,pictureBox7,
pictureBox8,pictureBox9,pictureBox10,pictureBox11,pictureBox12,pictureBox13,pictureBox14,pictureBox15,pictureBox16
};
picPuzzle = picturebox;
resizeImage();
cropImage();
shufflePuzzle();
}
public void shufflePuzzle()
{
int numberSelect;
int index = 0;
Point virtualLocation;
List<int> selected = new List<int>();
while (selected.Count < picPuzzle.Count)
{
int randomSelectPuzzle = rnd.Next(0, 16);
if (selected.Contains(randomSelectPuzzle))
{
randomSelectPuzzle = rnd.Next(0, 16);
}
else
{
numberSelect = randomSelectPuzzle;
virtualLocation = new Point(picPuzzle[numberSelect].Location.X, picPuzzle[numberSelect].Location.Y);
picPuzzle[numberSelect].Location = new Point(DefaultLocation.X, DefaultLocation.Y);
DefaultLocation = virtualLocation;
selected.Add(randomSelectPuzzle);
}
}
}
public void resizeImage()
{
Bitmap newImage = new Bitmap(320, 320);
Bitmap srcImage = new Bitmap(#"C:\Users\bbmm\Desktop\images\lukas-graham.jpg");
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, 320, 320));
}
this.newImage = newImage;
try
{
Bitmap bt = new Bitmap(newImage);
bt.Save(#"E:\img\pic.jpg");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void cropImage()
{
var filename = #"E:\img\pic.jpg";
Rectangle cropRect;
Bitmap[] src = new Bitmap[16];
Bitmap[] target = new Bitmap[16];
int x = 0, y = 0;
int index = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (index == 17)
{
return;
}
cropRect = new Rectangle(new Point(x, y), new Size(new Point(100, 100)));
src[index] = Image.FromFile(filename) as Bitmap;
target[index] = new Bitmap(cropRect.Width, cropRect.Height);
using (Graphics g = Graphics.FromImage(target[index]))
{
g.DrawImage(src[index], new Rectangle(0, 0, target[index].Width, target[index].Height), cropRect, GraphicsUnit.Pixel);
}
picPuzzle[index].Image = target[index];
x += 100;
index++;
}
y += 100;
x = 0;
}
}
public Point HoldLocation
{
get;
set;
}
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
move = e.Location;
}
public List<PictureBox> pastePics { get; set; }
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
PictureBox pb = (PictureBox)sender;
pb.Left += e.X - move.X;
pb.Top += e.Y - move.Y;
pb.BringToFront();
}
}
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
}
}
}

How can i use a trackBar scroll event to move between images fast and smooth?

This is the scroll event
int countver = 0;
int counthor = 0;
Image newImage;
private void trackBar2_Scroll(object sender, EventArgs e)
{
if (files != null && files.Length > 0)
{
newImage = Image.FromFile(files[files.Length - 1]);
float imghorizontal = newImage.HorizontalResolution;
float imgvertical = newImage.VerticalResolution;
if (trackBar2.Value < trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
if (trackBar2.Value == trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
pictureBox1.Image = ResizeImage(files[files.Length - 1], (int)imghorizontal + counthor, (int)imgvertical + countver);
label15.Text = (int)imghorizontal + counthor.ToString() + "," + (int)imgvertical + countver.ToString();
label15.Visible = true;
}
}
This is the method Resize Image
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
if (newWidth >= 0 && newHeight >= 0)
{
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
return null;
}
}
The problem is when i move the scroll up or down it's taking a 1-3 seconds to make the image process. And if i move the scroll up faster to another value it's taking even more(another vlaue i mean i'm trying to move the slider from the beginning to the end the program hang).
This is the form1 code i'm using a backgroundworker to change the images size on the hard disk. The whole idea is to give the user a preview of how the image/s will look like and then if he decide it's good enough he click a button that start the backgroundworker.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace Images_Batch_Resize
{
public partial class Form1 : Form
{
OpenFileDialog openFileDialog1;
string[] files;
string directoryPath;
public Form1()
{
InitializeComponent();
label6.Visible = false;
label7.Visible = false;
label8.Visible = false;
label9.Visible = false;
label10.Visible = false;
label12.Visible = false;
label15.Visible = false;
openFileDialog1 = new OpenFileDialog();
trackBar2.Minimum = 0;
trackBar2.Maximum = 20;
}
private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
//openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
pictureBox2.Load(files[0]);
pictureBox1.Load(files[0]);
trackBar1.Minimum = 0;
trackBar1.Maximum = files.Length - 1;
}
}
catch (IOException)
{
}
}
}
private void beginOperationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (files.Length > 0)
{
backgroundWorker1.RunWorkerAsync();
}
}
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
if (newWidth >= 0 && newHeight >= 0)
{
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
return null;
}
}
int countver = 0;
int counthor = 0;
Image newImage;
private void trackBar2_Scroll(object sender, EventArgs e)
{
if (files != null && files.Length > 0)
{
newImage = Image.FromFile(files[files.Length - 1]);
float imghorizontal = newImage.HorizontalResolution;
float imgvertical = newImage.VerticalResolution;
if (trackBar2.Value < trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
if (trackBar2.Value == trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
pictureBox1.Image = ResizeImage(files[files.Length - 1], (int)imghorizontal + counthor, (int)imgvertical + countver);
label15.Text = (int)imghorizontal + counthor.ToString() + "," + (int)imgvertical + countver.ToString();
label15.Visible = true;
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
pictureBox1.Load(files[trackBar1.Value]);
pictureBox2.Load(files[trackBar1.Value]);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
int counter = 0;
int percentage = 0;
foreach (string file in files)
{
Bitmap bmp1 = new Bitmap(ResizeImage(file, 300, 300));
string resizedfilename = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(file) + "_resized.jpg");
bmp1.Save(resizedfilename);
bmp1.Dispose();
counter++;
percentage = counter * 100 / files.Length;
worker.ReportProgress(percentage);
}
}
catch(Exception err)
{
string ttt = err.ToString();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
int oldValue = 0;
private void trackBar2_ValueChanged(object sender, EventArgs e)
{
if ((sender as TrackBar).Value >= oldValue)
{
}
else
{
}
oldValue = (sender as TrackBar).Value;
}
}
}

Getting values from mouse hover on a class object C#

I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color.
this is the code of the class:
class DatoDisco
{
int valoreSpicchio;
int gradi;
public DatoDisco(int valoreTastatore, int gradiLettura)
{
valoreSpicchio = valoreTastatore;
gradi = gradiLettura;
}
public void Clear()
{
valoreSpicchio = 0;
gradi = 0;
}
private int ScalaGrigi()
{
int grigio = 0;
if (valoreSpicchio <= 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio < 0)
grigio = 0;
}
if (valoreSpicchio > 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio > 230)
grigio = 230;
}
return grigio;
}
public void Paint (Graphics grafica)
{
try
{
Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi()));
grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f);
}
catch
{
}
}
public int ValoreSpicchio
{
get
{
return valoreSpicchio;
}
}
public int Gradi
{
get
{
return gradi;
}
}
}
here is where I draw everything:
public partial class Samac : Form
{
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
libnodave.daveConnection dc;
int rack = 0;
int slot = 2;
int scalaGrigi = 0;
int angolatura = 0;
List<int> valoriY = new List<int>();
//Disco disco = new Disco();
List<DatoDisco> disco = new List<DatoDisco>();
float[] valoriTastatore = new float[360];
public Samac()
{
InitializeComponent();
StreamReader dataStream = new StreamReader("save.txt");
textBox1.Text = dataStream.ReadLine();
dataStream.Dispose();
for (int i = 0; i <= 360; i++ )
chart1.Series["Series2"].Points.Add(0);
//AggiornaGrafico(textBox1.Text, chart1);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
string indirizzoIpPlc
{
get
{
FileIniDataParser parser = new FileIniDataParser();
IniData settings = parser.LoadFile("config.ini");
return settings["PLC_CONNECTION"]["PLC_IP"];
}
}
private void AggiornaGrafico(string nomeFile, Chart grafico, bool online)
{
int max = 0;
int min = 0;
grafico.Series["Series1"].Points.Clear();
grafico.Series["Series2"].Points.Clear();
grafico.Series["Series3"].Points.Clear();
grafico.Series["Series4"].Points.Clear();
grafico.ChartAreas[0].AxisX.Maximum = 360;
grafico.ChartAreas[0].AxisX.Minimum = 0;
grafico.ChartAreas[0].AxisY.Maximum = 500;
grafico.ChartAreas[0].AxisY.Minimum = -500;
String file = nomeFile;
valoriY.Clear();
disco.Clear();
if (online == false)
{
System.IO.File.WriteAllText("save.txt", nomeFile);
}
StreamReader dataStreamGrafico = new StreamReader(file);
StreamReader dataStreamScheda = new StreamReader("Scheda.sch");
string datasample;
string[] scheda = new string[56];
for (int i = 0; i < 56; i++)
{
scheda[i] = dataStreamScheda.ReadLine();
}
dataStreamScheda.Close();
int gradi = 1;
while ((datasample = dataStreamGrafico.ReadLine()) != null)
{
grafico.Series["Series2"].Points.Add(0);
grafico.Series["Series2"].Color = Color.Red;
grafico.Series["Series2"].BorderWidth = 3;
grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5])));
grafico.Series["Series3"].Color = Color.Green;
grafico.Series["Series3"].BorderWidth = 3;
grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5])));
grafico.Series["Series4"].Color = Color.Green;
grafico.Series["Series4"].BorderWidth = 3;
grafico.Series["Series1"].Points.Add(int.Parse(datasample));
grafico.Series["Series1"].BorderWidth = 5;
valoriY.Add(int.Parse(datasample));
//disco.Add(int.Parse(datasample));
disco.Add(new DatoDisco(int.Parse(datasample), gradi));
gradi++;
}
dataStreamGrafico.Close();
max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]);
min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]);
lblCampanatura.Text = (((float)max + min) / 2000.0).ToString();
lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString();
if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800))
{
if (Math.Abs(max) >= Math.Abs(min))
{
chart1.ChartAreas[0].AxisY.Maximum = max + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(max + 200);
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = min + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(min + 200);
}
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = 800;
chart1.ChartAreas[0].AxisY.Minimum = -800;
}
boxGraficaDisco.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
ToolTip tooltip = new ToolTip();
private int lastX;
private int lastY;
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20);
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1;
if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Il File non esiste");
}
}
private void btnGrafMeno_Click(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1;
if (indice >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Prima lettura disco");
}
}
private void btnConnetti_Click(object sender, EventArgs e)
{
fds.rfd = libnodave.openSocket(102, indirizzoIpPlc);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
di.setTimeout(1000000);
dc = new libnodave.daveConnection(di, 0, rack, slot);
int res = dc.connectPLC();
timer1.Start();
// AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
MessageBox.Show("Impossibile connettersi");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
int res;
res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null);
if (res == 0)
{
var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0;
if (letturaDati == true)
{
int puntatore = 30;
StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv");
datiDisco.WriteLine("X;" + "C;" + "Z;");
while (puntatore <= 10838)
{
res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null);
if (res == 0)
{
for (int i = 0; dc.getU32At(i) != 0; i = i + 12)
{
datiDisco.Write(dc.getU32At(i).ToString() + ";");
datiDisco.Write(dc.getU32At(i + 4).ToString() + ";");
datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";");
}
}
puntatore = puntatore + 192;
}
datiDisco.Close();
StreamReader lettura = new StreamReader("DatiDaPlc.csv");
StreamWriter scritt = new StreamWriter("Disco.csv");
var titolo = lettura.ReadLine();
var posizioneLettura = lettura.ReadLine();
var posX = posizioneLettura.Split(';');
int minX = Convert.ToInt32(posX[0]) - 5;
int maxX = Convert.ToInt32(posX[0]) + 5;
int contatore = 0;
while (!lettura.EndOfStream)
{
var line = lettura.ReadLine();
var values = line.Split(';');
if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX))
{
scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString());
contatore += 1000;
}
}
lettura.Close();
scritt.Close();
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
}
else
{
timer1.Stop();
MessageBox.Show("Disconnesso");
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
}
}
}
private void btnDisconnetti_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
timer1.Stop();
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void Samac_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closeSocket(102);
timer1.Stop();
}
}
private void button1_Click_2(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void chart2_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y));
//tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20);
tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20);
//chart2.Series[0].ToolTip="#VALY";
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void boxGraficaDisco_Paint(object sender, PaintEventArgs e)
{
Graphics grafica = e.Graphics;
//disco.Paint(grafica);
foreach (DatoDisco d in disco)
{
d.Paint(grafica);
}
}
private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
foreach (DatoDisco d in disco)
{
}
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
}
Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how.
Anyone can help me?
this is an image of the disc
Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc..
Here is a function to calculate an angle given two points:
double AngleFromPoints(Point pt1, Point pt2)
{
Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);
double alpha = 0d;
if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;
else
{
double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));
alpha = Math.Acos(f) * 180d / Math.PI;
if (P.Y > 0) alpha = 360d - alpha;
}
return alpha;
}

c# Bitmap.Save A generic error occurred in GDI+ windows application

I am doing OCR application. I have this error when I run the system which the system will save the picturebox3.image into a folder.
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
** ERROR occuer here!!!!!**
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg"); // error line occcur
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
Since it has been a while, I'm hoping you found your answer, but I'm going to guess that you needed to set the file format when you're saving a jpeg:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Past that, I can't remember if the picturebox control is double buffered or not which could be the problem (if it's not, you might not be able to access it for saving purposes while it is being rendered, but if you make a copy of area before setting the picturebox3.Image property that would fix that issue):
Bitmap SavingObject=new Bitmap(area);
picturebox3.Image=area;
SavingObject.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Anyway, I hope you ended up finding your solution (considering it's been a couple months since this was posted).
This looks like a copy of this question:
c# A generic error occurred in GDI+
Same code, same error, same author.
Can't see any difference. But maybe I'm missing something.

Categories