Display photo taken with kinect at runtime in C# - c#

I am taking an image with Kinect in C# and want to display it on the next page of the application.
I can acquire the image successfully and can store it successfully on disk since I'm able to send this image as an email attachment.
The photo acquisition code is:
public void CaptureScreen(double x, double y, double width, double height)
{
int ix, iy, iw, ih;
ix = Convert.ToInt32(x);
iy = Convert.ToInt32(y);
iw = Convert.ToInt32(width);
ih = Convert.ToInt32(height);
// set the kinect hand icon invisible
kinectButton.Visibility = System.Windows.Visibility.Collapsed;
kinectButton2.Visibility = System.Windows.Visibility.Collapsed;
Bitmap image = new Bitmap(iw, ih,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(ix, iy, ix, iy,
new System.Drawing.Size(iw, ih),
CopyPixelOperation.SourceCopy);
image.Save("../../Images/image_display.png");
desk_input();
}
I use the image_display.png file to display the image on the screen.
I'm using the following code for displaying the image:
private void desk_input() {
BitmapImage bi2 = new BitmapImage();
bi2.BeginInit();
bi2.UriSource = new Uri("/Images/image_display.png", UriKind.RelativeOrAbsolute);
bi2.EndInit();
photo_preview.Visibility = System.Windows.Visibility.Visible;
photo_preview.Source = bi2;
Canvas.SetLeft(photo_preview, 750);
Canvas.SetTop(photo_preview, 400);
}
However, during run time, the photo taken when the application was run last time keeps being displayed instead of the current photo. I'm guessing this is because the image_display.png file is added to the binary when the application is compiled.
So can you suggest a way where I can display the image taken with the kinect immediately?
Edit: I solved the problem by refreshing the bitmap cache as follows:
private void desk_input() {
BitmapImage bi2 = new BitmapImage();
bi2.BeginInit();
bi2.UriSource = new Uri("/Images/image_display.png", UriKind.RelativeOrAbsolute);
bi2.CacheOption = BitmapCacheOption.OnLoad; //Changed - Reload the file
bi2.EndInit();
photo_preview.Visibility = System.Windows.Visibility.Visible;
photo_preview.Source = bi2;
Canvas.SetLeft(photo_preview, 750);
Canvas.SetTop(photo_preview, 400);
}

Related

Displaying multiple screen in a picturebox c#

Im quite new at c# and i've been searching and searching for an answer on my stupid problem and I cant seem to find it. Here it goes:
I'm creating a simple snipping tool program that I want to capture all monitor screens connected. When I start the program I have 2 monitors running. But the picturebox shows both screens only on one screen
How do I solve this so they appear as snipping tool does?
The code:
private void Form1_Load(object sender, EventArgs e)
{
ActiveForm.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEscKeyPress);
//Hide the Form
this.Hide();
int screenLeft = SystemInformation.VirtualScreen.Left;
int screenTop = SystemInformation.VirtualScreen.Top;
int screenWidth = SystemInformation.VirtualScreen.Width;
int screenHeight = SystemInformation.VirtualScreen.Height;
this.Size = new System.Drawing.Size(screenWidth, screenHeight);
this.Location = new System.Drawing.Point(screenLeft, screenTop);
//Create the Bitmap
//Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
// Screen.PrimaryScreen.Bounds.Height);
Bitmap printscreen = new Bitmap(SystemInformation.VirtualScreen.Width,
SystemInformation.VirtualScreen.Height,
PixelFormat.Format32bppArgb);
//Create the Graphic Variable with screen Dimensions
Graphics graphics = Graphics.FromImage(printscreen as Image);
//Copy Image from the screen
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
using (MemoryStream s = new MemoryStream())
{
//save graphic variable into memory
printscreen.Save(s, System.Drawing.Imaging.ImageFormat.Bmp);
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
pictureBox1.Size = new System.Drawing.Size(this.Width, this.Height);
//set the picture box with temporary stream
pictureBox1.Image = Image.FromStream(s);
}
//this.Location = Screen.AllScreens[1].WorkingArea.Location;
this.Location = new System.Drawing.Point(screenLeft, screenTop);
//this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Show();
//Cross Cursor
Cursor = Cursors.Cross;
}

Cannot Cast png to bitmap

I'm attempting to convert a image to bitmap so that i can make it rotate based on angles received through the serial port, and then output the resultant image to a pictureBox. however this results in either a build failure or the image wont show on the screen. i am using the AForge Imaging.Filters framework to achieve this. current code:
private void imageRotate(int angle)
{
int angleToMove = angle; //- lastAngle;
Bitmap image = Properties.Resources.Compass_Transparent;
pictureBox1.Image = null;
RotateBilinear ro = new RotateBilinear(angleToMove, true);
ro.FillColor = Color.White;
pictureBox1.BackColor = Color.White;
Bitmap image2 = ro.Apply(image);
pictureBox1.Image = image2;
lastAngle = angle;
}
i am able to achieve the desired effect by using
Bitmap image = (Bitmap)Image.FromFile(#"path");
and i can currently set the pictureBox to the image initially by using
img = TableTurner.Properties.Resources.Compass_Transparent;
pictureBox1.Image = img;
however this does not work when trying to reference the resources file.

Adding dynamic text to image

I currently have an image which gets displayed to the user, I'm trying to add dynamic text to this image based on two parameters passed in.
The issue I have is when I step through the code it all seems to be working correctly, however when I see the image on the screen after the below code has run it doesn't have the text on it.
Below is my current set up of code:
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
int phWidth = imgBackground.Width; int phHeight = imgBackground.Height;
Bitmap bmBackground = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmBackground.SetResolution(72, 72);
Graphics grBackground = Graphics.FromImage(bmBackground);
Bitmap bmWatermark;
Graphics grWatermark;
bmWatermark = new Bitmap(bmBackground);
bmWatermark.SetResolution(imgBackground.HorizontalResolution, imgBackground.VerticalResolution);
grWatermark = Graphics.FromImage(bmWatermark);
grBackground.SmoothingMode = SmoothingMode.AntiAlias;
// Now add the dynamic text to image
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
grWatermark.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
grWatermark.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}
As mentioned after this code has run, I then see the image in the browser however text is not displayed on the image, can anyone see / suggest what maybe causing this issue?
I feel like there are way to many images in that code for what you are describing as the intent of the code. What you want should reduce to this:
Load Image
Create Graphics on that Image
Draw into the Graphics and close
Output image to client
In the code sample you provided you are opening the Graphics on imgBackground then drawing into the grWatermark graphics which is opened earlier on against an image you never touch again.
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
graphics.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
graphics.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}

Remove darkness in capturing image background in winform c#

I have worked on image capture window application. When I have captured image by application in window tablet then image quality low and show darkness in captured image background. When I have captured image by tablet then image is good quality.
What is missing/problem in my code?
I have used code share by you...
private void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
ImgContainer.Image = b;
}
private void btnKeep_Click(object sender, EventArgs e)
{
int width = 457;
int height = 350;
Image tmpimg = ImgContainer.Image;
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ImgContainer.Image, width, height);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(b);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
string ImagePath = Guid.NewGuid().ToString();
string imagefullpath = System.AppDomain.CurrentDomain.BaseDirectory + "imageFolder\\" + ImagePath + ".jpg";
b.Save(imagefullpath);
}
Show you captured by application image ............
Show you captured by tablet ............
Please give me any idea and solution remove darkness captured by application (above image).
You can use a DrawImage with an ImageAttributes instance to change the gamma. I found 0.5f to work:
Here is a function that applies a gamma value to a bitmap and returns a modified bitmap. It is up to you to ..:
make sure you don't leak resources
make sure to apply the gamma always to the original and not repeatedly to the same bitmap when giving the user a trackbar to find a good value..
The function:
public static Bitmap ApplyGamma(Bitmap bmp0, float gamma)
{
Bitmap bmp1 = new Bitmap(bmp0.Width, bmp0.Height);
using (Graphics g = Graphics.FromImage(bmp1))
{
ImageAttributes attributes = new ImageAttributes();
attributes.SetGamma(gamma, ColorAdjustType.Bitmap);
g.DrawImage(bmp0, new Rectangle(0, 0, bmp0.Width, bmp0.Height),
0, 0, bmp0.Width, bmp0.Height, GraphicsUnit.Pixel, attributes);
}
return bmp1;
}
The calling code I used:
Image img = Image.FromFile(yourImage); // some image to use
float gamma = (float)(trackBar1.Value / 10f); // a trackbar to test
Text = "Gamma = " + gamma; // a control display
pictureBox1.Image = ApplyGamma((Bitmap)img, gamma);
If you also want to change contrast and/or brightness you can use a ColorMatrix. See here for an example!

C# .net screencapture from hidden site. [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
A graph is being generated in a webpage. I am trying to do a screen capture with C# code. I tried the code below. It worked a few times and now I get "index was out of range. must be non-negative and less than the size of the collection" error.
Any help or guidance is appreciated. Thanks in advance.
System.Drawing.Bitmap bitMap = null;
static AutoResetEvent autoEvent;
public void DownloadAsImage(string title, string location)
{
autoEvent = new AutoResetEvent(false);
Uri url = HttpContext.Current.Request.Url;
string RootUrl = url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);
//ApartmentState:specifies the state of a system.threading.thread
//STA:Thread will create and enter a single-threaded apartment
Thread t = new Thread(CaptureWebPageToDisplay);
t.SetApartmentState(ApartmentState.STA);
if (title == "PieGraph" && location == "0")
{
t.Start(RootUrl + "/_Layouts/AppPage/Reports/TotalGraphPage.aspx?isdlg=1");
Thread.Sleep(30000);
}
else
{
t.Start(RootUrl + "/_Layouts/AppPage/Reports/GraphPage.aspx?isdlg=1&Title=" + title + "&Location=" + location);
Thread.Sleep(10000);
}
autoEvent.Set();
HttpContext.Current.Response.ContentType = "image/jpeg";
string targetFolder = Server.MapPath(#".\GraphImages\") + title + ".Jpeg";
try
{
bitMap.Save(targetFolder);
bitMap.Dispose();
}
catch(Exception ex){
DBLogger.ExpandException(ex);
if (bitMap != null)
{
bitMap.Dispose();
}
}
}
public void CaptureWebPageToDisplay(object URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// Full web browser
web.Dock = System.Windows.Forms.DockStyle.Fill;
web.Size = new System.Drawing.Size(1000, 800);
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate((string)URL);
// wait until the page is fully loaded
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(5000); // allow time for page scripts to update
// the appearance of the page
// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// change background color to white, just in case
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.Clear(System.Drawing.Color.White);
// create rectangle.
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(20, 0, width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, rect);
bitMap = bmp;
}
I think the following code to capture a screen might help :
public static void CaptureScreen(double x, double y, double width, double height)
{
int ix, iy, iw, ih;
ix = Convert.ToInt32(x);
iy = Convert.ToInt32(y);
iw = Convert.ToInt32(width);
ih = Convert.ToInt32(height);
Bitmap image = new Bitmap(iw, ih,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(ix, iy, ix, iy,
new System.Drawing.Size(iw, ih),
CopyPixelOperation.SourceCopy);
// Download Image
image.Save(FileName, ImageFormat.Png);
}

Categories