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);
}
Related
I have a windows forms project written in C#. The main form has a TabControl on it and there is a requirement for one of the users to be able to print one of the TabPages. The form is very long and I use a vertical scroll bar. The whole of the form needs to be able to be printed.
I have tried using the DrawToBitmap method to convert to a bitmap first, but this will only include the portion of the form that the user can see. Some other solutions I have tried involve screen capturing, which has the same issue.
How can I print out, or get an image, of the whole of the tab page, including the parts the user only sees when they scroll down?
This is rather simple for any control including TabControls and TabPages but not Forms.
All you need to do is enlarge the relevant controls enough to show all their content. (They don't have to be actually visible on screen.)
Here is an example:
tabControl1.Height = 10080;
tabPage2.Height = 10050;
dataGridView1.Height = 10000;
dataGridView1.Rows.Add(3000);
for (int i = 0; i < dataGridView1.Rows.Count; i++) dataGridView1[0, i].Value = i;
using (Bitmap bmp = new Bitmap(tabControl1.Width , tabControl1.Height ))
{
tabControl1.DrawToBitmap(bmp, tabControl1.ClientRectangle);
bmp.Save("D:\\xxxx.png", ImageFormat.Png);
}
This saves the full content of the DataGridView, the TabPage and the TabControl..
Note: that this will not work with forms, which can't much exceed the screen dimensions..
Update: Here is code that saves a form with vertical scrolling by patching several bitmaps together. It can, of course be expanded to include horizontal scrolling as well. I have coded a similar solution for larger Panels here.
static void saveLargeForm(Form form, string fileName)
{
// yes it may take a while
form.Cursor = Cursors.WaitCursor;
// allocate target bitmap and a buffer bitmap
Bitmap target = new Bitmap(form.DisplayRectangle.Width, form.DisplayRectangle.Height);
Bitmap buffer = new Bitmap(form.Width, form.Height);
// the vertical pointer
int y = 0;
var vsc = form.VerticalScroll;
vsc.Value = 0;
form.AutoScrollPosition = new Point(0, 0);
// the scroll amount
int l = vsc.LargeChange;
Rectangle srcRect = ClientBounds(form);
Rectangle destRect = Rectangle.Empty;
bool done = false;
// we'll draw onto the large bitmap with G
using (Graphics G = Graphics.FromImage(target))
{
while (!done)
{
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
int v = vsc.Value;
vsc.Value = vsc.Value + l;
form.AutoScrollPosition = new Point(form.AutoScrollPosition.X, vsc.Value + l);
int delta = vsc.Value - v;
done = delta < l;
y += delta;
}
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
}
// write result to disc and clean up
target.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
target.Dispose();
buffer.Dispose();
GC.Collect(); // not sure why, but it helped
form.Cursor = Cursors.Default;
}
It makes use of a helper function to determine the the net size of the virtual client rectangle, ie excluding borders, title and scrollbar:
static Rectangle ClientBounds(Form f)
{
Rectangle rc = f.ClientRectangle;
Rectangle rb = f.Bounds;
int sw = SystemInformation.VerticalScrollBarWidth;
var vsc = f.VerticalScroll;
int bw = (rb.Width - rc.Width - (vsc.Visible ? sw : 0) ) / 2;
int th = (rb.Height - rc.Height) - bw * 2;
return new Rectangle(bw, th + bw, rc.Width, rc.Height );
}
How do I save a generated thumbnail? I am getting this error:
Object reference not set to an instance of an object
This is my code. I am new to C#. I found the thumbnail generation code online and I thought I could use it but its giving me an error...
//1. <lcFilename> as path of large size file.
//2. <lnWidth> as width of required thumbnail.
//3. <lnHeight> as height of required thumbnail.
//The function returns a Bitmap object of the changed thumbnail image which you can save on the disk.
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
//*** If the image is smaller than a thumbnail just return it
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
// Thumbnail Generate
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
You have to Dispose your Graphics after it finishes its job. When you draw something on an image with Graphics, it is common to use using block but since it is already in the try/catch scope, it seems redundant here.
//1. <lcFilename> as path of large size file.
//2. <lnWidth> as width of required thumbnail.
//3. <lnHeight> as height of required thumbnail.
//The function returns a Bitmap object of the changed thumbnail image which you can save on the disk.
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
//*** If the image is smaller than a thumbnail just return it
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
// Dispose Graphics so that it releases all the resources it's holding to draw on that image.
g.Dispose();
/* or you could use Graphics as below.. but it seems redundant, because it is already in the try / catch block.
using ( Graphics g = Graphics.FromImage(bmpOut))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
}
*/
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
// Thumbnail Generate
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
The problem is you have a try..catch inside your method and this is swallowing the exception, and you are returning null from there, Hence the exception that you have reported.
Option 1
My suggestion is to either do something with the exception such as log it, this way you know something went wrong, like now. And handle the instance where a null value can be returned by the method, as follows:
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
if (bmp1 == null) {
// there was an exception, check the logs
}
else {
bmp1.Save(largefilepath2);
}
Option 2:
Or remove the try catch completely from the method and move it out as follows:
Note: the following code assumes you have removed the try...catch from the CreateThumbnail method.
try {
//Where imageUploaded is the name of the image with the extension, e.g. "samplePic.jpg"
string largefilepath = #"c:\images\" + imageuploaded;
string largefilepath2 = #"c:\images\users\" + System.IO.Path.GetFileNameWithoutExtension(imageuploaded) + "-160x160" + System.IO.Path.GetExtension(largefilepath);
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
}
catch (Exception ex) {
//do something with the exception
}
I am trying to create a bitmap and all I have is the savedUri and the imagePath. I believe I am retrieving the imagePath correctly because when I go and look at the actual properties of the photos of the photo and the logged path they are the same so I believe it is a problem in the way I'm creating the bitmap. Here is the code I use:
if (_bitmap == null)
{
string imagePath = null;
try
{
imagePath = GetRealPathFromURI(_saveUri);
LogManager.Info("********the image path is", imagePath);
}
catch
{
imagePath = _saveUri.Path;
}
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile(imagePath, options);
var width = (int)Math.Round(_outputX * 0.5);
var heigth = (int)Math.Round(_outputY * 0.5);
options.InSampleSize = BitmapTools.CalculateInSampleSize(options, width, width * heigth);
options.InJustDecodeBounds = false;
options.InDensity = 160;
try
{
_bitmap = BitmapFactory.DecodeFile(imagePath, options);
}
catch
{
GC.Collect();
_bitmap = BitmapFactory.DecodeFile(imagePath, options);
}
}
if (_bitmap == null)
LogManager.Info("********the bitmap width is: ", "well bloody hell the bitmap is null");
else
LogManager.Info("********the bitmap width is: ", _bitmap.Width.ToString());
On the last two lines the bitmap is never null but it always has a width of 1 and when I display it there is no image. This is for creating, displaying and saving an image on Monodroid but that isn't too relevant to this question as it is.
When I take screenshots with ChromeDriver I get screens with the size of my viewport.
When I take screenshots with FirefoxDriver I get what I want, which is a full screen print of a website.
ChromeDriver is declared like this:
IWebDriver driver = new ChromeDriver();
FirefoxDriver is declared like this:
IWebDriver driver = new FirefoxDriver();
Both drivers execute identical code:
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl(url);//url is a string variable
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
screenshot.SaveAsFile("c:/test.png", ImageFormat.Png);
ChromeDriver's test.png is of 1920x1099 resolution and contains only the browser viewport.
FirefoxDriver's test.png is of 1903x16559 resolution and contains the whole page.
I know that GetScreenshot() method doesn't return identical resolution sizes because it has slightly different implementations in IEDriver, FirefoxDriver, OperaDriver, ChromeDriver.
My questions are:
Why is there such difference between ChromeDriver's and FirefoxDriver's .GetScreenshot() method, even tho they use an identical interface (ITakesScreenshot)?
Is there a way to make ChromeDriver's GetScreenshot() method return the whole webpage screen instead of just the viewport?
we can't get the entire page screenshot with ChromeDriver2, we need to go for manual implementation.I have modified a method with is available in a blog which works fine with ChromeDriver.
use this method as following :
private IWebDriver _driver = new ChromeDriver(CHROME_DRIVER_PATH);
screenshot.SaveAsFile(saveFileName, ImageFormat.Jpeg);
public Bitmap GetEntereScreenshot()
{
Bitmap stitchedImage = null;
try
{
long totalwidth1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.offsetWidth");//documentElement.scrollWidth");
long totalHeight1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.parentNode.scrollHeight");
int totalWidth = (int)totalwidth1;
int totalHeight = (int)totalHeight1;
// Get the Size of the Viewport
long viewportWidth1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.clientWidth");//documentElement.scrollWidth");
long viewportHeight1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return window.innerHeight");//documentElement.scrollWidth");
int viewportWidth = (int)viewportWidth1;
int viewportHeight = (int)viewportHeight1;
// Split the Screen in multiple Rectangles
List<Rectangle> rectangles = new List<Rectangle>();
// Loop until the Total Height is reached
for (int i = 0; i < totalHeight; i += viewportHeight)
{
int newHeight = viewportHeight;
// Fix if the Height of the Element is too big
if (i + viewportHeight > totalHeight)
{
newHeight = totalHeight - i;
}
// Loop until the Total Width is reached
for (int ii = 0; ii < totalWidth; ii += viewportWidth)
{
int newWidth = viewportWidth;
// Fix if the Width of the Element is too big
if (ii + viewportWidth > totalWidth)
{
newWidth = totalWidth - ii;
}
// Create and add the Rectangle
Rectangle currRect = new Rectangle(ii, i, newWidth, newHeight);
rectangles.Add(currRect);
}
}
// Build the Image
stitchedImage = new Bitmap(totalWidth, totalHeight);
// Get all Screenshots and stitch them together
Rectangle previous = Rectangle.Empty;
foreach (var rectangle in rectangles)
{
// Calculate the Scrolling (if needed)
if (previous != Rectangle.Empty)
{
int xDiff = rectangle.Right - previous.Right;
int yDiff = rectangle.Bottom - previous.Bottom;
// Scroll
//selenium.RunScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
((IJavaScriptExecutor)_driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
System.Threading.Thread.Sleep(200);
}
// Take Screenshot
var screenshot = ((ITakesScreenshot)_driver).GetScreenshot();
// Build an Image out of the Screenshot
Image screenshotImage;
using (MemoryStream memStream = new MemoryStream(screenshot.AsByteArray))
{
screenshotImage = Image.FromStream(memStream);
}
// Calculate the Source Rectangle
Rectangle sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);
// Copy the Image
using (Graphics g = Graphics.FromImage(stitchedImage))
{
g.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
}
// Set the Previous Rectangle
previous = rectangle;
}
}
catch (Exception ex)
{
// handle
}
return stitchedImage;
}
I cleaned up #Selvantharajah Roshanth's answer and added a check so that it won't try to stitch together screenshots that already fit in the viewport.
public Image GetEntireScreenshot()
{
// Get the total size of the page
var totalWidth = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.offsetWidth"); //documentElement.scrollWidth");
var totalHeight = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.parentNode.scrollHeight");
// Get the size of the viewport
var viewportWidth = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.clientWidth"); //documentElement.scrollWidth");
var viewportHeight = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return window.innerHeight"); //documentElement.scrollWidth");
// We only care about taking multiple images together if it doesn't already fit
if (totalWidth <= viewportWidth && totalHeight <= viewportHeight)
{
var screenshot = driver.TakeScreenshot();
return ScreenshotToImage(screenshot);
}
// Split the screen in multiple Rectangles
var rectangles = new List<Rectangle>();
// Loop until the totalHeight is reached
for (var y = 0; y < totalHeight; y += viewportHeight)
{
var newHeight = viewportHeight;
// Fix if the height of the element is too big
if (y + viewportHeight > totalHeight)
{
newHeight = totalHeight - y;
}
// Loop until the totalWidth is reached
for (var x = 0; x < totalWidth; x += viewportWidth)
{
var newWidth = viewportWidth;
// Fix if the Width of the Element is too big
if (x + viewportWidth > totalWidth)
{
newWidth = totalWidth - x;
}
// Create and add the Rectangle
var currRect = new Rectangle(x, y, newWidth, newHeight);
rectangles.Add(currRect);
}
}
// Build the Image
var stitchedImage = new Bitmap(totalWidth, totalHeight);
// Get all Screenshots and stitch them together
var previous = Rectangle.Empty;
foreach (var rectangle in rectangles)
{
// Calculate the scrolling (if needed)
if (previous != Rectangle.Empty)
{
var xDiff = rectangle.Right - previous.Right;
var yDiff = rectangle.Bottom - previous.Bottom;
// Scroll
((IJavaScriptExecutor) driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
}
// Take Screenshot
var screenshot = driver.TakeScreenshot();
// Build an Image out of the Screenshot
var screenshotImage = ScreenshotToImage(screenshot);
// Calculate the source Rectangle
var sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);
// Copy the Image
using (var graphics = Graphics.FromImage(stitchedImage))
{
graphics.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
}
// Set the Previous Rectangle
previous = rectangle;
}
return stitchedImage;
}
private static Image ScreenshotToImage(Screenshot screenshot)
{
Image screenshotImage;
using (var memStream = new MemoryStream(screenshot.AsByteArray))
{
screenshotImage = Image.FromStream(memStream);
}
return screenshotImage;
}
It appears as though full-screen screenshots are not yet implemented in the ChromeDriver, due to some inaccuracies in its previous implementation.
Source: https://code.google.com/p/chromedriver/issues/detail?id=294
I have recently written a Selenium based application to test an Internet Explorer UI and found that:
Taking screenshots with selenium was not as quick as using .NET, and
Selenium is unable to take screenshots when dialog boxes are present. This was a major drawback, as I needed to identify unexpected dialogs during interaction with the pages.
Investigate using the Graphics.CopyFromScreen method in System.Drawing as an alternative solution until the feature is implemented in Chrome. Once you have tried .the Net approach however, I don't think you will look back =]
I stumbled accross the same problem and ChromeDriver2 just does not support it.
So I created a little script which scrolls thru the page, takes screenshots and stitches everything together.
You can find the script in my blog post here:
http://dev.flauschig.ch/wordpress/?p=341
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);
}