I found a class to make a gif file containing multiple frame animations run in front of a background image. This is my class:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace AnimSprites {
public class AnimSprite {
private int frame, interval, width, height;
private string imgFile;
private Image img;
private Timer frameTimer;
public AnimSprite(string f_imgFile, int f_width) {
frame = 0;
width = f_width;
imgFile = f_imgFile;
img = new Bitmap(imgFile);
height = img.Height;
}
public void Start(int f_interval) {
interval = f_interval;
frameTimer = new Timer();
frameTimer.Interval = interval;
frameTimer.Tick += new EventHandler(advanceFrame);
frameTimer.Start();
}
public void Start() {
Start(100);
}
public void Stop() {
frameTimer.Stop();
frameTimer.Dispose();
}
public Bitmap Paint(Graphics e) {
Bitmap temp;
Graphics tempGraphics;
temp = new Bitmap(width, height, e);
tempGraphics = Graphics.FromImage(temp);
tempGraphics.DrawImageUnscaled(img, 0-(width*frame), 0);
tempGraphics.Dispose();
return(temp);
}
private void advanceFrame(Object sender, EventArgs e) {
frame++;
if ( frame >= img.Width/width )
frame = 0;
}
}
}
How can I use this class to make my gif file (running_dog.gif) run over background.jpg from left to right?
This is the dog.gif file: dog.gif
The class you've included expects the animation frames to go from left to right rather than top to bottom as your .gif does.
You can alter it by changing the constructor to
public AnimSprite(string f_imgFile, int f_height) {
frame = 0;
height = f_height;
imgFile = f_imgFile;
img = new Bitmap(imgFile);
width = img.Width;
}
and the advanceFrame method to
private void advanceFrame(Object sender, EventArgs e) {
frame++;
if ( frame >= img.Height/height )
frame = 0;
}
}
and your call to DrawImageUnscaled to
tempGraphics.DrawImageUnscaled(img, 0, 0-(height*frame));
Related
In paint event because i want to be able to control the dots size colors and more properties.
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class LoadingLabel : UserControl
{
public LoadingLabel()
{
InitializeComponent();
}
private void LoadingLabel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red, 1, 1, 20, 20);
Thread.Sleep(1);
e.Graphics.FillEllipse(Brushes.Red, 1, 1, 0, 0);
Thread.Sleep(1);
}
}
I tried first to make a simple dot that is disappearing after some time and then show again but it's not working i see a red still dot(point).
later when this will work i want to make 3 dots animating like a loading animation.
This is what I've tried:
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class LoadingLabel : UserControl
{
private bool animate = false;
public LoadingLabel()
{
InitializeComponent();
timer1.Enabled = true;
}
private void LoadingLabel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if (animate == false)
{
e.Graphics.FillEllipse(Brushes.Red, 1, 1, 20, 20);
}
else
{
e.Graphics.FillEllipse(Brushes.Red, 5, 1, 20, 20);
}
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count++;
if(count == 10 && animate == false)
{
animate = true;
}
if(count == 20 && animate)
{
animate = false;
count = 0;
}
this.Invalidate();
}
}
the result is the first point draw then the second point draw but the first one is gone:
it looks like the point is moving to the right and back to the left.
but i want a loading effect with 3 points. and not moving point.
This is working with 3 points but it looks too complicated for 3 points. and if i want 100 points?
maybe i should use a loop inside the paint event ?
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class LoadingLabel : UserControl
{
private int numofpoints = 0;
public LoadingLabel()
{
InitializeComponent();
timer1.Enabled = true;
}
private void LoadingLabel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if(numofpoints == 0)
{
e.Graphics.FillEllipse(Brushes.Red, 1, 1, 20, 20);
}
if(numofpoints == 1)
{
e.Graphics.FillEllipse(Brushes.Red, 5, 1, 20, 20);
}
if(numofpoints == 2)
{
e.Graphics.FillEllipse(Brushes.Red, 10, 1, 20, 20);
}
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count++;
if(count == 10)
{
numofpoints = 0;
}
if(count == 20)
{
numofpoints = 1;
}
if(count == 30)
{
numofpoints = 2;
count = 0;
}
this.Invalidate();
}
}
Another update of what I've tried:
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class LoadingLabel : UserControl
{
private List<PointF> points = new List<PointF>();
public LoadingLabel()
{
InitializeComponent();
points.Add(new PointF(0, 0));
timer1.Enabled = true;
}
private void LoadingLabel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
for (int i = 0; i < points.Count; i++)
{
e.Graphics.FillEllipse(Brushes.Red, points[i].X, points[i].Y, 20, 20);
}
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count++;
if (count < 3)
{
points.Add(new PointF(count * 20, 0));
//points = new List<PointF>();
}
//this.Invalidate();
}
}
If i will make the instance in the tick event it will not draw anything. if i will use the Invalidate line it will make the points to be like blinking.
what i want is to create a loading effect animation.
the result as the code now is still 3 points, and i want to animate them like in the link.
Something like this:
Since, based on the image you have posted, you want to animate a series of Dots, where only the active one changes color, your UserControl can define Properties that allow to specify the number of Dots, the Color of a Dot and the Color of the active Dot.
A Timer can be used to change the current active Dot, so the paint procedure knows when to change the color of one of the Dots.
The UserControl is automatically resized when the number of Dots specified changes.
Also when the UserControl is first created, it sets its MinimumSize, so the Dots are always visible.
You can expand on this template, adding more features.
Note these lines in the Constructor of the UserControl:
components = new Container();
dotsTimer = new Timer(components) { ... };
This instructs the Timer Component to add itself to the Components of the Parent container, so when the Parent is disposed, the Timer is also disposed and its event handler(s) removed.
Setting DoubleBuffered = true; avoids flickering when the Dots are drawn.
Call the Start() method to start the animation and the Stop() method to, well, stop it.
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class LoadingLabel : UserControl {
private int m_NumberOfDots = 5;
private Color m_DotColor = Color.Cyan;
private Color m_DotActiveColor = Color.Blue;
private float dotSize = 20.0f;
private float dotSpacing = 20.0f;
private int currentDot = 0;
private Timer dotsTimer = null;
public LoadingLabel()
{
InitializeComponent();
components = new Container();
dotsTimer = new Timer(components) { Interval = 200 };
dotsTimer.Tick += DotsTimer_Tick;
DoubleBuffered = true;
Padding = new Padding(5);
}
[DefaultValue(5)]
public int NumberOfDots {
get => m_NumberOfDots;
set {
value = Math.Max(3, Math.Min(value, 7));
if (m_NumberOfDots != value) {
m_NumberOfDots = value;
bool running = dotsTimer.Enabled;
Stop();
SetMinSize();
if (running) Start();
}
}
}
[DefaultValue(typeof(Color), "Cyan")]
public Color DotColor {
get => m_DotColor;
set {
m_DotColor = value;
Invalidate();
}
}
[DefaultValue(typeof(Color), "Blue")]
public Color DotActiveColor {
get => m_DotActiveColor;
set {
m_DotActiveColor = value;
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
for (int dot = 0; dot < m_NumberOfDots; dot++) {
var color = dot == currentDot ? DotActiveColor : DotColor;
var pos = Padding.Left + (dotSize + dotSpacing) * dot;
using (var brush = new SolidBrush(color)) {
e.Graphics.FillEllipse(brush, pos, Padding.Top, dotSize, dotSize);
}
}
base.OnPaint(e);
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
SetMinSize();
}
protected override void OnHandleDestroyed(EventArgs e) {
Stop();
base.OnHandleDestroyed(e);
}
private void DotsTimer_Tick(object sender, EventArgs e) {
currentDot += 1;
currentDot %= m_NumberOfDots;
Invalidate();
}
public void Start() => dotsTimer.Start();
public void Stop() {
dotsTimer.Stop();
currentDot = 0;
Invalidate();
}
private void SetMinSize() {
var width = Padding.Left + Padding.Right +
(dotSize * m_NumberOfDots) + (dotSpacing * (m_NumberOfDots - 1)) + 1;
var height = Padding.Top + Padding.Bottom + dotSize + 1;
MinimumSize = new Size((int)width, (int)height);
Size = MinimumSize;
}
}
This is how it works:
On demand, this is the PasteBin of the custom ComboBox Control used to select a Color.
A single call to the Paint method/event should draw the control as it is supposed to look at that instant. If you wish to add animation, you should make the control redraw itself repeatedly and use some internal state to keep track of the animation.
This little program opens a windows form and draws 70 red rectangles, where the user clicks on the form.
Every time the user clicks, the rectangles disappear, and new ones are drawn on the new click-Point.
I want to make the rectangles to stay when the user clicks and draws a new set of rectangles.
How do i do that?
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;
namespace tegnRektangel
{
public partial class Form1 : Form
{
int x;
int y;
bool mouseClicked = false;
Graphics g = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
}
private void Form1_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (mouseClicked)
{
g = panel1.CreateGraphics();
paintRectangel();
}
}
private void paintRectangel()
{
for (int i = 1; i <= 70; i++)
{
g.DrawRectangle(Pens.Red, x - 50-i*5, y - 40-i*5, 100, 80);
}
g.Dispose();
}//end paint
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
mouseClicked = true;
Point clickPoint = new Point(e.X,e.Y);
x = clickPoint.X;
y = clickPoint.Y;
panel1.Invalidate();
}
}
}
From MSDN:
The Graphics object that you retrieve through the CreateGraphics
method should not normally be retained after the current Windows
message has been processed, because anything painted with that object
will be erased with the next WM_PAINT message.
You can work around it like this:
In the click event, add the (x, y) coordinate to a list of coordinates.
In the paint event, iterate all these (x, y) coordinates and paint each rectangle.
Here is some code to demonstrate creating rectangles for each click, storing them, and painting all stored rectangles.
public partial class Form1 : Form
{
private List<Rectangle> Rectangles { get; set; }
public Form1()
{
InitializeComponent();
Rectangles = new List<Rectangle>();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (Rectangles.Count > 0)
e.Graphics.DrawRectangles(Pens.Red, Rectangles.ToArray());
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
for (int i = 1; i <= 70; i++)
{
Rectangles.Add(new Rectangle(e.X - 50 - i * 5, e.Y - 40 - i * 5, 100, 80));
}
Invalidate();
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace UTUResultWithCoordinates
{
public partial class GetCoordinates : Form
{
private string sem;
private string branch;
private int mouseisdown = 0;
private int recx = 0;
private int recy = 0;
private int mousemovingwhilepressed = 0;
public GetCoordinates()
{
InitializeComponent();
}
public GetCoordinates(string p, string p_2)
{
// TODO: Complete member initialization
InitializeComponent();
branch = p;
sem = p_2;
pictureBox1.Controls.Add(pictureBox2);
pictureBox2.Location = new Point(0, 0);
pictureBox2.BackColor = Color.Transparent;
pictureBox2.Width = 1191;
pictureBox2.Height = 842;
}
private void GetCoordinates_Load(object sender, EventArgs e)
{
pictureBox1.ImageLocation = #"D:\DotNet\UTUResultWithCoordinates\UTUResultWithCoordinates\bin\Debug\ComputerScience6.jpg";
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
if (mouseisdown == 1 && mousemovingwhilepressed==1)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Blue, 100);
Rectangle myRectangle = new Rectangle(recx, recy, 20, 20);
e.Graphics.DrawRectangle(myPen, myRectangle);
}
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
mouseisdown = 1;
recx = e.X;
recy = e.Y;
pictureBox2.CreateGraphics();
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = e.X + "," + e.Y;
mousemovingwhilepressed = 1;
recx = e.X;
recy = e.Y;
pictureBox2.CreateGraphics();
}
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
mousemovingwhilepressed = 0;
mouseisdown = 0;
pictureBox2.CreateGraphics();
}
}
}
I have created a pictureBox1 in which an image is displayed. Then I have created a pictureBox2 inside it so that I can paint on that image a rectangle by dragging the mouse. But nothing is happening on clicking the mouse. What is the error?
Calling CreateGraphics does not trigger the painting of the PictureBox.
Use Invalidate to cause a redraw.
For a full example see: How to select an area on a PictureBox.Image with mouse in C#
Side notes:
Calling InitializeControl in a method other than the constructor is not a good idea.
when you need a boolean use a boolean, not an integer.
Objects that implement IDisposable (such as Pen) should be created as few times as possible and be disposed when no longer needed/used.
I have a flag in the Form1 top level: addFrame wich is set to false in the constructor.
Then in the picnt event i check if its false let me draw if its true also let me draw. The problem here is that i want to be able to draw when im running the program first time !
But when im moving the trackBar to the right i dont want it to draw anything .
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
moveCounter++;
label6.Text = moveCounter.ToString();
if (addFrame == false)
{
WireObjectGraphics.Draw(wireObject1, g);
}
else
{
addFrame = false;
WireObjectGraphics.Draw(wireObject1, g);
}
}
This is the button click event where im clicking to set the addFrame to true:
private void button16_Click(object sender, EventArgs e)
{
wireObjectAnimation1.AddFrame();
addFrame = true;
trackBar1.Select();
}
And the scroll bar event in this case i want to make that if i move the trackBar to the right and there are no any draws already then just show the image in the pictureBox dont draw anything ! But if i move it to the right and there are already draws then do show them.
If i move it to the left allways show the previous draws.
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (addFrame == false)
{
}
else
{
currentFrameIndex = trackBar1.Value - 1;
textBox1.Text = "Frame Number : " + trackBar1.Value;
wireObject1.woc.Set(wireObjectAnimation1.GetFrame(currentFrameIndex));
trackBar1.Minimum = 0;
trackBar1.Maximum = fi.Length - 1;
if (checkBox1.Checked)
{
setpicture(trackBar1.Value);
Graphics g = Graphics.FromImage(pictureBox1.Image);
g.Clear(SystemColors.Control);
pictureBox1.Invalidate();
}
else
{
setpicture(trackBar1.Value);
}
pictureBox1.Refresh();
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button8.Enabled = false;
SaveFormPicutreBoxToBitMapIncludingDrawings(currentFrameIndex);
return;
}
}
This is the draw function in the WireObjectGraphics class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace AnimationEditor
{
class WireObjectGraphics
{
static Point connectionPointStart;
static Point connectionPointEnd;
static SolidBrush brush;
static Pen p = null;
public WireObjectGraphics()
{
}
public static void Draw(WireObject wo, Graphics graphics)
{
brush = new SolidBrush(Color.Red);
p = new Pen(brush);
Graphics g = graphics;
WireObject wireObject1 = wo;
if (wireObject1 != null)
{
for (int idx = 0; idx < wireObject1.woc.Point_X.Count; ++idx)
{
Point dPoint = new Point((int)wireObject1.woc.Point_X[idx], (int)wireObject1.woc.Point_Y[idx]);
dPoint.X = dPoint.X - 5; // was - 2
dPoint.Y = dPoint.Y - 5; // was - 2
Rectangle rect = new Rectangle(dPoint, new Size(10, 10));
g.FillEllipse(brush, rect);
// bitmapGraphics.FillEllipse(brush, rect);
// g.FillEllipse(brush, rect);
}
for (int i = 0; i < wireObject1._connectionstart.Count; i++)
{
int startIndex = wireObject1._connectionstart[i];
int endIndex = wireObject1._connectionend[i];
connectionPointStart = new Point((int)wireObject1.woc.Point_X[startIndex], (int)wireObject1.woc.Point_Y[startIndex]);
connectionPointEnd = new Point((int)wireObject1.woc.Point_X[endIndex], (int)wireObject1.woc.Point_Y[endIndex]);
p.Width = 2;
g.DrawLine(p, connectionPointStart, connectionPointEnd);
// bitmapGraphics.DrawLine(p, connectionPointStart, connectionPointEnd);
}
}
}
}
}
What i need is that first time running the program to be able to draw !
Then when moving the trackBar to the righ to check if draws already exists show them if not exist show only the image and only when i click the button it will add the draws on the frame im on.
If i move to the left allways show the draws i did in the other frames.
WireObject class:
Constructor:
class WireObject
{
private string an;
private bool fnExt;
public string lockObject;
private int idx;
public WireObjectCoordinates woc;
private List<int> connectionStart = new List<int>();
private List<int> connectionEnd = new List<int>();
private const string version = "01.00";
string wo_name;
public WireObject( string name )
{
wo_name = name;
woc = new WireObjectCoordinates();
fnExt = false;
}
In the wireobject class i have some function like connecting points(pixels) like delete pixels like save and load...
WireObjectCoordinates class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AnimationEditor
{
class WireObjectCoordinates
{
public List<float> Point_X = new List<float>();
public List<float> Point_Y = new List<float>();
public WireObjectCoordinates()
{
}
public WireObjectCoordinates(WireObjectCoordinates w)
{
Point_X.AddRange(w.Point_X);
Point_Y.AddRange(w.Point_Y);
}
public void Set(WireObjectCoordinates w)
{
if (w == null)
{
}
else
{
for (int i = 0; i < Point_X.Count; i++)
{
Point_X[i] = w.Point_X[i];
Point_Y[i] = w.Point_Y[i];
}
}
}
}
}
The problem is still in Form1 with the flag when to show the pixels i mean when and how to call the paint event like pictureBox1.Refresh(); but oncei t will use the Draw function inside and once it will not. When i run the program let me use the draw function once i moved the trackBar to the right dont use the draw function.
For a windows form control OnPaint is only called when a.) a window overlapping the current control is moved out of the way OR b.) you manually invalidate the control : http://msdn.microsoft.com/en-us/library/1e430ef4.aspx
So OnPaint should be getting called too often.
I've tried converting vb.net to C# but I keep getting error while compiling. I am new to .NET.
This is my version of converted image utilities class. Util.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Com.Griaule.IcaoFace;
using System.Windows.Forms;
namespace IcaoWF
{
public class Util
{
//Set if the mouth is important
public const bool USES_MOUTH = true;
//The number of supported pictures
const int SFile = 3;
//
public const int FEATURES_COLOR = (255 << 8);
public const int FEATURES_SIZE = 8;
//File Vector with spec ID
TFile[] VTFile = new TFile[SFile + 1];
//Pointers to the .NET classes
public FaceImage GrFaceImage = null;
public IcaoImage GrIcaoImage = null;
public CbeffImage GrCbeffImage = null;
public Cbeff GrCbeff = null;
ListBox log;
// raw image data type.
public struct TRawImage
{
// Image data.
public object img;
// Image width.
public int width;
// Image height.
public int height;
//Reduction Factor because stretch
public float frX;
public float frY;
//Eyes an mouth positions
public int lx;
public int ly;
public int rx;
public int ry;
public int mx;
public int my;
}
// File Enum Type
public enum EFile
{
BMP = 1,
JPEG2000 = 2,
CBEFF = 3,
NOTDEF = 0
}
//File Type
private struct TFile
{
//File Extension
public string fileExt;
//File Type
public EFile fileID;
}
//Class constructor
public Util(ListBox ltBox)
{
//Adding Supportted files
VTFile[1].fileExt = ".bmp";
VTFile[1].fileID = EFile.BMP;
VTFile[2].fileExt = ".jp2";
VTFile[2].fileID = EFile.JPEG2000;
VTFile[3].fileExt = ".cbeff";
VTFile[3].fileID = EFile.CBEFF;
log = ltBox;
}
public void WriteError(GriauleIcaoFaceException err)
{
WriteLog("Error: " + err.ToString());
}
// Write a message in box.
public void WriteLog(string message)
{
log.Items.Add(message);
log.SelectedIndex = log.Items.Count - 1;
log.ClearSelected();
}
//Get the ID File Type from file path name
public EFile GetFileType(string fileName)
{
EFile functionReturnValue = default(EFile);
int i = 0;
for (i = 0; i <= SFile; i++)
{
if (Strings.InStr(1, fileName, VTFile[i].fileExt) == Strings.Len(fileName) - Strings.Len(VTFile[i].fileExt) + 1)
{
functionReturnValue = VTFile[i].fileID;
return functionReturnValue;
}
}
functionReturnValue = EFile.NOTDEF;
return functionReturnValue;
}
//Loading an Image
public bool LoadImage(string fileName, PictureBox img)
{
// create face image from file
GrFaceImage = new FaceImage(fileName);
// display face image
DisplayFaceImage(img, false);
WriteLog("Image loaded successfully.");
return true;
}
//Process the raw Image to FaceImage Type and paint the points on pBox
public bool ProcessFaceImage(PictureBox pBox)
{
//Set mouth to be relevant to generate the ICAO
GrFaceImage.MouthDetectionEnabled = USES_MOUTH;
WriteLog("Finding the eyes and mouth positions. Please, wait...");
//Get the positions from mouth and eyes
if (GetPositionsFromFaceImage())
{
WriteLog("Eyes and mouth founded. Drawing their positions on the image.");
//Display Face Image with eyes and mouth drawn
DisplayFaceImage(pBox, true);
return true;
}
else
{
//Display Face Image
DisplayFaceImage(pBox, false);
return false;
}
}
//Display the ICAO Image
public void DisplayIcaoImg(PictureBox imgIcao)
{
if (GrFaceImage.LeftEye.X <= 0 | GrFaceImage.LeftEye.Y <= 0 | GrFaceImage.LeftEye.X > GrFaceImage.Width | GrFaceImage.LeftEye.Y > GrFaceImage.Height)
{
WriteLog("Left eye is out of bounds.");
return;
}
if (GrFaceImage.RightEye.X <= 0 | GrFaceImage.RightEye.Y <= 0 | GrFaceImage.RightEye.X > GrFaceImage.Width | GrFaceImage.RightEye.Y > GrFaceImage.Height)
{
WriteLog("Right eye is out of bounds.");
return;
}
if (GrFaceImage.Mouth.X <= 0 | GrFaceImage.Mouth.Y <= 0 | GrFaceImage.Mouth.X > GrFaceImage.Width | GrFaceImage.Mouth.Y > GrFaceImage.Height)
{
WriteLog("Mouth is out of bounds.");
return;
}
//Get the GrIcaoImage
try
{
GrIcaoImage = GrFaceImage.FullFrontalImage(imgIcao.Width, 3.0 / 4.0, IcaoImage.IcaoFullFrontalMode.FullFrontal);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
return;
}
//Getting the eyes positons from icao
if (GetPositionsFromIcaoImage())
{
//Displaying the icao image
DisplayIcaoImage(imgIcao);
}
WriteLog("ICAO image generated.");
}
//Display Face Image
public void DisplayFaceImage(PictureBox pBox, bool withFeatures)
{
if (withFeatures)
{
pBox.Image = GrFaceImage.ImageWithFeatures(8, Color.Green);
}
else
{
pBox.Image = GrFaceImage.Image;
}
pBox.Update();
}
//Display Cbeff Image
public void DisplayCbeffImage(PictureBox pBox)
{
pBox.Image = GrCbeffImage.Image;
pBox.Update();
}
//Display Icao Image
public void DisplayIcaoImage(PictureBox pBox)
{
pBox.Image = GrIcaoImage.Image;
pBox.Update();
}
//Save ICAO in CBEFF file format
public void SaveIcaoIntoCBEFFImage(string fileName)
{
// Create a CBEFF from Icao
if (GetCbeffFromIcao())
{
//Get the CBEFF buffer
try
{
SaveBuffer(fileName, ref GrCbeff.CBEFF);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
}
}
}
//Load an ICAO image from CBEFF file format
public void LoadIcaoFromCBEFFImage(string fileName, PictureBox pBox)
{
//Creating the cbeff from the buffer
try
{
GrCbeff = new Cbeff(LoadBuffer(fileName));
GrCbeffImage = GrCbeff.Image(0);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
}
// Display icao image
DisplayCbeffImage(pBox);
}
//Save ICAO image in JPEG2000 file format
public void SaveIcaoIntoJP2Image(string fileName)
{
// Create a CBEFF from Icao
if (!GetCbeffFromIcao())
{
return;
}
//Get Jpeg2000 buffer from CBEFF and save it in a file
SaveBuffer(fileName, ref GrCbeffImage.BufferJPEG);
}
//Save Byte Buffer into a file
private void SaveBuffer(string fileName, ref byte[] buffer)
{
System.IO.FileStream oFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
System.IO.BinaryWriter swb = new System.IO.BinaryWriter(oFileStream);
swb.Write(buffer);
swb.Close();
}
//Load stream from file
private byte[] LoadBuffer(string fileName)
{
// Open a file that is to be loaded into a byte array
FileInfo oFile = null;
oFile = new FileInfo(fileName);
System.IO.FileStream oFileStream = oFile.OpenRead();
long lBytes = oFileStream.Length;
byte[] fileData = new byte[lBytes + 1];
// Read the file into a byte array
oFileStream.Read(fileData, 0, lBytes);
oFileStream.Close();
return fileData;
}
//Get CBEFF image from an Icao image
private bool GetCbeffFromIcao()
{
//Create Cbeff Image Data pointer
GrCbeff = new Cbeff();
GrCbeffImage = GrCbeff.AddImage(GrIcaoImage, false, 0);
GrCbeffImage.Gender = CbeffImage.CbeffGender.Unknown;
GrCbeffImage.Eyes = CbeffImage.CbeffEyes.Unspecified;
GrCbeffImage.Hair = CbeffImage.CbeffHair.Unspecified;
GrCbeffImage.FeatureMask = 0;
GrCbeffImage.Expression = CbeffImage.CbeffExpression.Unspecified;
return true;
}
//Get eyes and mouth position from Face Image
public bool GetPositionsFromFaceImage()
{
float prob = 0;
//Get the eyes detection probabilty
prob = GrFaceImage.DetectionProbability;
if (prob == 0)
{
Interaction.MsgBox("There isn't any probability to find the eyes position.", Constants.vbCritical, "No probability");
return false;
}
return true;
}
//Get eyes and mouth position from ICAO Image
public bool GetPositionsFromIcaoImage()
{
//get the position from an icao image.
float prob = 0;
prob = GrIcaoImage.DetectionProbability;
if (prob <= 0)
{
WriteLog("There isn't any probability to find the eyes position.");
return false;
}
return true;
}
//Set left eye position on library
public void SetLeftEyePos(int x, int y)
{
GrFaceImage.LeftEye = new Point(x, y);
}
//Set right eye position on library
public void SetRightEyePos(int x, int y)
{
GrFaceImage.RightEye = new Point(x, y);
}
//Set mouth position on library
public void SetMouthPos(int x, int y)
{
if (x > 0 & x < GrFaceImage.Width & y > 0 & y < GrFaceImage.Height)
{
Point p = new Point(x, y);
GrFaceImage.Mouth = p;
}
}
//Marshal between library and VB .NET. Copy an Variant Array to Byte() vector
public byte[] ConvertArrayToVByte(Array buffer)
{
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
byte[] bytes = new byte[buffer.Length + 1];
Marshal.Copy(ptr, bytes, 0, bytes.Length);
return bytes;
}
// Show GriauleAfis version and type
public void MessageVersion()
{
int majorVersion = 0;
int minorVersion = 0;
GriauleIcaoFace.GetVersion(majorVersion, minorVersion);
MessageBox.Show("The GrIcaoFace DLL version is " + majorVersion + "." + minorVersion + ".", "GrIcaoFace Version", MessageBoxButtons.OK);
}
}
}
I keep get error with this error:
The type or namespace name 'ListBox' could not be found (are
you missing a using directive or an assembly reference?).
The type or namespace name 'PictureBox' could not be found (are you
missing a using directive or an assembly reference?).
And here is the formMain.cs
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IcaoWF
{
public partial class formMain : Form
{
public formMain(): base()
{
Load += formMain_Load;
InitializeComponent();
}
// raw image data type.
private struct TSetting
{
// Image data.
public Button button;
// Image width.
public Label x;
public Label y;
public bool setting;
}
TSetting CSetting = new TSetting();
Util myUtil = default(Util);
private void formMain_Load(Object sender, EventArgs e)
{
InitializeInterface();
//Setting file filters
ldImg.Filter = "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)|*.gif|Bitmaps (*.bmp)|*.bmp";
ldIcaoImg.Filter = "CBEFF (*.cbeff)|*.cbeff";
svIcaoImg.Filter = "JPEG2000 (*.jp2)|*.jp2|CBEFF (*.cbeff)|*.cbeff";
myUtil = new Util(logBox);
//Verifieing if the mouth is important
gbMouth.Enabled = myUtil.USES_MOUTH;
}
//Unlock the interface and update the clicked iten
private void interfaceSetStop(int x, int y)
{
if (CSetting.setting) {
//Set the CSetting to false
CSetting.setting = false;
//Set positions from mouse to CSetting text selected
CSetting.x.Text = x.ToString();
CSetting.y.Text = y.ToString();
//Enable Set button again
CSetting.button.Enabled = true;
//Set the normal cursor above image
imgFace.Cursor = Cursors.Arrow;
//Enable all butons, disabled before
EnableButtons();
//Sets new position from image
myUtil.SetLeftEyePos(lbLeftEyeXPos.Text, lbLeftEyeYPos.Text);
myUtil.SetRightEyePos(lbRightEyeXPos.Text, lbRightEyeYPos.Text);
if (myUtil.USES_MOUTH) {
myUtil.SetMouthPos(lbMouthXPos.Text, lbMouthYPos.Text);
}
//Redraw img
myUtil.DisplayFaceImage(imgFace, true);
}
}
//Initialize the program interface
private void InitializeInterface()
{
//Disable butons
DisableButtons();
//Disbable image picture box
imgFace.Enabled = false;
//Current setting eye or mouth to false
CSetting.setting = false;
//Disable Save ICAO image
mnFileSaveIcaoImg.Enabled = false;
//Reset the logBox
logBox.ResetText();
}
//Enable all butons from interface
private void EnableButtons()
{
btGenIcaoImage.Enabled = true;
btLeftEyeSet.Enabled = true;
btMouthSet.Enabled = true;
btRightEyeSet.Enabled = true;
btProcess.Enabled = true;
imgFace.Enabled = true;
}
//Set the inteface to click on the image
private void btLeftEyeSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btLeftEyeSet, lbLeftEyeXPos, lbLeftEyeYPos);
}
//Set the inteface to click on the image
private void lbRightEyeSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btRightEyeSet, lbRightEyeXPos, lbRightEyeYPos);
}
//Set the inteface to click on the image
private void btMouthSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btMouthSet, lbMouthXPos, lbMouthYPos);
}
//Lock the interface to click on image
private void interfaceSetStart(Button button, Label x, Label y)
{
//Set the clicked button set
CSetting.button = button;
//set the label to update the position
CSetting.x = x;
CSetting.y = y;
//Enable set mode
CSetting.setting = true;
//Disable the button
button.Enabled = false;
//Enable Cross cursor on image
imgFace.Cursor = Cursors.Cross;
//Disable button to avoid user to click in another area
DisableButtons();
}
//Disable all buttons from interface
private void DisableButtons()
{
btGenIcaoImage.Enabled = false;
btLeftEyeSet.Enabled = false;
btMouthSet.Enabled = false;
btRightEyeSet.Enabled = false;
btProcess.Enabled = false;
}
//On click on the image, stop the interface and set the right position
private void imgFace_MouseDown(object sender, MouseEventArgs e)
{
interfaceSetStop(e.X / (imgFace.Width / myUtil.GrFaceImage.Width), e.Y / (imgFace.Height / myUtil.GrFaceImage.Height));
}
//Gen the ICAO image from FaceImage
private void btGenIcaoImage_Click(Object sender, EventArgs e)
{
//Display ICAO image captured
myUtil.DisplayIcaoImg(imgIcaoImg);
//Enabled
mnFileSaveIcaoImg.Enabled = true;
}
//Load Icao IMAGE From CBEFF or JPEG2000
private void mnFileLoadIcaoImg_Click(Object sender, EventArgs e)
{
Util.EFile fileType = default(Util.EFile);
ldIcaoImg.FileName = "";
//save the ICAO image
if (ldIcaoImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(ldIcaoImg.FileName))
{
fileType = myUtil.GetFileType(ldIcaoImg.FileName);
switch (fileType)
{
case Util.EFile.CBEFF:
//Save CBEFF image
myUtil.LoadIcaoFromCBEFFImage(ldIcaoImg.FileName, imgIcaoImg);
break;
//
default:
//Image type not found
myUtil.WriteLog("File type not supported.");
return;
}
}
}
//Save ICAO Image
private void mnFileSaveIcaoImg_Click(Object sender, EventArgs e)
{
Util.EFile fileType = default(Util.EFile);
svIcaoImg.FileName = "";
//save the ICAO image
if (svIcaoImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(svIcaoImg.FileName))
{
fileType = myUtil.GetFileType(svIcaoImg.FileName);
switch (fileType)
{
case Util.EFile.CBEFF:
//Save CBEFF image
myUtil.SaveIcaoIntoCBEFFImage(svIcaoImg.FileName);
break;
case Util.EFile.JPEG2000:
//Save JPEG200 image
myUtil.SaveIcaoIntoJP2Image(svIcaoImg.FileName);
break;
default:
//Image type not found
myUtil.WriteLog("File type not supported.");
break;
}
}
}
//Load Image
private void mnFileLoadImg_Click(Object sender, EventArgs e)
{
lbLeftEyeXPos.Text = "0";
lbLeftEyeYPos.Text = "0";
lbRightEyeXPos.Text = "0";
lbRightEyeYPos.Text = "0";
lbMouthXPos.Text = "0";
lbMouthYPos.Text = "0";
//Disable buttons
DisableButtons();
//Enable image
imgFace.Enabled = true;
//Set file name image to null
ldImg.FileName = "";
if (ldImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(ldImg.FileName))
{
//load image from FileName into imgFace Picture Box
if (myUtil.LoadImage(ldImg.FileName, imgFace))
{
//Set the icaoImage to null
imgIcaoImg.Image = null;
imgIcaoImg.Refresh();
//Disble mnFileSaveIcaoImg to save
mnFileSaveIcaoImg.Enabled = false;
//Disable buttons
DisableButtons();
//Enable find eyes and mouth button
btProcess.Enabled = true;
}
}
}
//Close the program
private void MenuItem5_Click(Object sender, EventArgs e)
{
this.Close();
}
//Process the Face Image
private void btProcess_Click(Object sender, EventArgs e)
{
//Enable buttons to set eyes and mouth
EnableButtons();
//Process face image
if (myUtil.ProcessFaceImage(imgFace))
{
//Get positions from face image
lbLeftEyeXPos.Text = myUtil.GrFaceImage.LeftEye.X.ToString();
lbLeftEyeYPos.Text = myUtil.GrFaceImage.LeftEye.Y.ToString();
lbRightEyeXPos.Text = myUtil.GrFaceImage.RightEye.X.ToString();
lbRightEyeYPos.Text = myUtil.GrFaceImage.RightEye.Y.ToString();
lbMouthXPos.Text = myUtil.GrFaceImage.Mouth.X.ToString();
lbMouthYPos.Text = myUtil.GrFaceImage.Mouth.Y.ToString();
}
}
//Print the DLL version
private void mnVersion_Click(Object sender, EventArgs e)
{
myUtil.MessageVersion();
}
}
}
I can post the vb.net version if needed.
EDITED: I have added refference(System.Windows.Forms.dll) to the project and all the other am using.
thanx
Nurcky
ListBox is defined in the assembly System.Windows.Forms.dll. Make sure you have a reference to that assembly.
Additionally you probably want
using System.Windows.Forms;
Both the ListBox and PictureBox controls are found in the System.Windows.Forms namespace. Add the following statement to the top of your code:
using System.Windows.Forms;
Then add a reference to System.Windows.Forms.dll
Use the System.Windows.Forms namespace. To use the System.Windows.Forms namespace, you have to add System.Windows.Forms.dll as a reference.
To add the reference,follow the following step:
In Solution Explorer, right-click on the project node and click Add Reference.
In the Add Reference dialog box, select the .NET tab and choose System.Windows.Forms and click OK.