I'm currently trying to make a screen recorder in C#. Right now I have it where the video file and audio files are both successfully made, but I can't figure out how to merge them. This is what I have so far:
public void Stop()
{
int width = bounds.Width;
int height = bounds.Height;
var framRate = 30;
//Save audio:
string audioPath = "save recsound " + outputPath + "\\mic.wav";
record(audioPath, "", 0, 0);
record("close recsound", "", 0, 0);
using (var vFWriter = new VideoFileWriter())
{
//Create new video file:
vFWriter.Open(outputPath + "//video.mp4", width, height, framRate, VideoCodec.MPEG4);
//Make each screenshot into a video frame:
foreach (var imageLocation in inputImageSequence)
{
Bitmap imageFrame = System.Drawing.Image.FromFile(imageLocation) as Bitmap;
vFWriter.WriteVideoFrame(imageFrame);
imageFrame.Dispose();
}
//Add audio:
byte[] audioByte = File.ReadAllBytes(outputPath + "\\mic.wav");
vFWriter.WriteAudioFrame(audioByte);
//Close:
vFWriter.Close();
}
//Delete the screenshots and temporary folder:
DeletePath(tempPath);
}
I don't get any errors, however the audio just isn't being added to the video.mp4. Any help is appreciated!
Related
Here is my code below which i am using to redraw and save the image.
Bitmap bitmap = new Bitmap(HttpContext.Current.Server.MapPath(
filePath + Path.GetFileName(fileName)));
int newWidth = 100;
int newHeight = 100;
int iwidth = bitmap.Width;
int iheight = bitmap.Height;
if (iwidth <= 100)
newWidth = iwidth;
if (iheight <= 100)
newHeight = iheight;
bitmap.Dispose();
// ONCE WE GOT ALL THE INFORMATION, WE'll NOW PROCESS IT.
// CREATE AN IMAGE OBJECT USING ORIGINAL WIDTH AND HEIGHT.
// ALSO DEFINE A PIXEL FORMAT (FOR RICH RGB COLOR).
System.Drawing.Image objOptImage = new System.Drawing.Bitmap(newWidth, newHeight,
System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
// GET THE ORIGINAL IMAGE.
using (System.Drawing.Image objImg =
System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filePath + fileName)))
{
// RE-DRAW THE IMAGE USING THE NEWLY OBTAINED PIXEL FORMAT.
using (System.Drawing.Graphics oGraphic = System.Drawing.Graphics.FromImage(objOptImage))
{
var _1 = oGraphic;
System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
_1.DrawImage(objImg, oRectangle);
}
// On the below lines of code i am getting error while i try to execute
// this code after uploading image. If image size is around 10 kb it will
// not throw any error but if it exceeds then 10 kb then it will.
//SAVE THE OPTIMIZED IMAGE
objOptImage.Save(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + fileName),
System.Drawing.Imaging.ImageFormat.Png);**
objImg.Dispose();
}
objOptImage.Dispose();
// FINALLY SHOW THE OPTIMIZED IMAGE DETAILS WITH SIZE.
Bitmap bitmap_Opt = new Bitmap(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));
byte[] bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));
UI.BasePage.TemporaryFile = bytes;
String[] ArrContentType = new String[] { postedFile.ContentType, fileName };
UI.BasePage.TemporaryStrings = ArrContentType;
int iwidth_Opt = bitmap_Opt.Width;
int iheight_Opt = bitmap_Opt.Height;
bitmap_Opt.Dispose();
I am uploading multiple photos using MultipleFileUpload, if I will upload big size images, then in slider image is not fixed size not showing proper looks. Is there any code for while uploading time restricts the size of images of the gallery.
Below is my c# code:
protected void lnkbtn_Submit_Click(object sender, EventArgs e)
{
try
{
if (MultipleFileUpload.HasFiles)
{
int MaxGalleryId, ReturnValue;
ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
if (ReturnValue != 0)
{
string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(GalleryPath));
string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(ThumbnailPath));
StringBuilder UploadedFileNames = new StringBuilder();
foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
{
//Upload file
string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
uploadedFile.SaveAs(SaveAsImage);
//Create thumbnail for uploaded file and save thumbnail on disk
Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
Thumbnail.Save(SaveAsThumbnail);
}
HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
}
}
}
catch
{
HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
}
}
Below is my Create Thumbnail method code :
public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
{
System.Drawing.Bitmap Thumbnail = null;
try
{
Bitmap ImageBMP = new Bitmap(ImagePath);
ImageFormat loFormat = ImageBMP.RawFormat;
decimal lengthRatio;
int ThumbnailNewWidth = 0;
int ThumbnailNewHeight = 0;
decimal ThumbnailRatioWidth;
decimal ThumbnailRatioHeight;
// If the uploaded image is smaller than a thumbnail size the just return it
if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
return ImageBMP;
// Compute best ratio to scale entire image based on larger dimension.
if (ImageBMP.Width > ImageBMP.Height)
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewWidth = ThumbnailWidth;
decimal lengthTemp = ImageBMP.Height * lengthRatio;
ThumbnailNewHeight = (int)lengthTemp;
}
else
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewHeight = ThumbnailHeight;
decimal lengthTemp = ImageBMP.Width * lengthRatio;
ThumbnailNewWidth = (int)lengthTemp;
}
Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
Graphics g = Graphics.FromImage(Thumbnail);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
ImageBMP.Dispose();
}
catch
{
return null;
}
return Thumbnail;
}
The above code there is a command line //Upload file from there uploading images. I used this example for the gallery:
http://www.bugdebugzone.com/2013/10/create-dynamic-image-gallery-slideshow.html
You can the ContentLength property of uploadedFile as such:
if (uploadedFile.ContentLength > 1000000)
{
continue;
}
ContentLength is the size in bytes of the uploaded file.
https://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contentlength(v=vs.110).aspx
i want to watermark pictures with different sizes in one folder. the watermark has 3891 x 4118 pixels. the pictures i want to watermark have nearly the same size or way lower.
however, the watermark image should always have the same size on the images. therefore i take the width of image i want to watermark, multiple it by 0.2 (20%) and the height of the watermark image gets calculated by the ratio. (see code below).
after that, i resize the watermark image and put it on on the image i want to watermark. so far so good, but the problem is, that the image is way smaller than it should be. the calculation works fine, even if i say, put the image as is (3891 x 4118 pixel), it calculates it correctly, but the watermark doesn't get bigger. it stays on a size i didn't calulcate.
that's the button to load the folder.
private void DateiLaden_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
try
{
string[] files = GetFiles(fbd.SelectedPath.ToString(), "*.jpg|*.jpeg"); //Only select JPG pictures, method below
int anzahlBilder = files.Length;
if (anzahlBilder <= 0)
{
System.Windows.Forms.MessageBox.Show("No images!");
} // if there are no images, stop processing...
else
{
var res = checkImageSize(files); //check if they have a minmal size, method below
if (res == "") //if everythings fine, continue
{
Directory.CreateDirectory(fbd.SelectedPath.ToString() + "\\watermarked"); //create new directory of the selected folder, folder so save the watermarked images
System.Drawing.Image brand = System.Drawing.Image.FromFile("../../watermark.png"); //load watermark
double imageHeightBrand = Convert.ToDouble(brand.Height); //get height (4118px)
double imageWidthBrand = Convert.ToDouble(brand.Width); //get width (3891px)
double ratioBrand = imageWidthBrand / imageHeightBrand; //get ratio (0.94487615347)
foreach (var file in files)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(file); //load image to watermerk to get width and height
double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
double imageWidthBild = Convert.ToDouble(img.Width); //width of the image to watermark
//Landscape
if (imageWidthBild > 640.0 && imageHeightBild > 425.0)
{
var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio
int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding); //convert in into int32 (see method below)
var watermark = ResizeImage(brand, imageWidthBranding, imageHeightBranding); //resize temporally the watermark image, method below
System.Drawing.Image image = System.Drawing.Image.FromFile(file); //get image to watermark
Graphics g = Graphics.FromImage(image); //load is as graphic
g.DrawImage(watermark, new System.Drawing.Point(50, 50)); //draw the watermark on it
image.Save(fbd.SelectedPath.ToString() + "\\watermarked\\" + returnOnlyImageName(file)); //save it in the folder with the same file name, see method below.
}
//Portrait
/* if(imageWidthBild > 350 && imageHeightBild > 520) {
}*/
}
}
else
{
System.Windows.Forms.MessageBox.Show(res);
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
"methods below"
private static string[] GetFiles(string sourceFolder, string filters)
{
return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter)).ToArray();
}
private static string checkImageSize(string[] files)
{
string message = "The following pictures are too small:\n";
foreach (var file in files)
{
Bitmap img = new Bitmap(file);
var imageHeight = img.Height;
var imageWidth = img.Width;
if ((imageWidth < 640 && imageHeight < 425) || (imageWidth < 350 && imageHeight < 520))
{
message += returnOnlyImageName(file) + "\n";
}
}
if (message == "The following pictures are too small:\n")
{
return "";
}
else
{
message += "\nPlease change those pictures!";
return message;
}
}
private static string returnOnlyImageName(string file)
{
return file.Substring(file.LastIndexOf("\\")+1);
}
public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
var destRect = new System.Drawing.Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
and is it also anyhow possible to save all the watermarks in the bottom right corner?
thanks in regards
Here you go...
void waterMarkOnBottomRight(Image img, Image watermarkImage, string saveFileName)
{
double imageHeightBrand = Convert.ToDouble(watermarkImage.Height);
double imageWidthBrand = Convert.ToDouble(watermarkImage.Width);
double ratioBrand = imageWidthBrand / imageHeightBrand;
double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
double imageWidthBild = Convert.ToDouble(img.Width);
var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio
int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding);
int watermarkX = (int)(imageWidthBild - imageWidthBranding); // Bottom Right
int watermarkY = (int)(imageHeightBild - imageHeightBranding);
using (Graphics g = Graphics.FromImage(img))
g.DrawImage(watermarkImage,
new Rectangle(watermarkX, watermarkY, imageWidthBranding, imageHeightBranding),
new Rectangle(0, 0, (int)imageWidthBrand, (int)imageHeightBrand),
GraphicsUnit.Pixel);
img.Save(saveFileName);
}
This one's working for landscape (width > height).
Well.. in your code, you don't have to create separate instances for images for calculating, for creating graphics, add a new bitmap and paint using graphics and all. You do anything with the image, its in the memory. And its not going to affect the watermark image on your disk.
I'm saving a bitmap to a file on my hard drive inside of a loop (All the jpeg files within a directory are being saved to a database). The save works fine the first pass through the loop, but then gives the subject error on the second pass. I thought perhaps the file was getting locked so I tried generating a unique file name for each pass, and I'm also using Dispose() on the bitmap after the file get saved. Any idea what is causing this error?
Here is my code:
private string fileReducedDimName = #"c:\temp\Photos\test\filePhotoRedDim";
...
foreach (string file in files)
{
int i = 0;
//if the file dimensions are big, scale the file down
Stream photoStream = File.OpenRead(file);
byte[] photoByte = new byte[photoStream.Length];
photoStream.Read(photoByte, 0, System.Convert.ToInt32(photoByte.Length));
Image image = Image.FromStream(new MemoryStream(photoByte));
Bitmap bm = ScaleImage(image);
bm.Save(fileReducedDimName + i.ToString() + ".jpg", ImageFormat.Jpeg);//error occurs here
Array.Clear(photoByte,0, photoByte.Length);
bm.Dispose();
i ++;
}
...
Thanks
Here's the scale image code: (this seems to be working ok)
protected Bitmap ScaleImage(System.Drawing.Image Image)
{
//reduce dimensions of image if appropriate
int destWidth;
int destHeight;
int sourceRes;//resolution of image
int maxDimPix;//largest dimension of image pixels
int maxDimInch;//largest dimension of image inches
Double redFactor;//factor to reduce dimensions by
if (Image.Width > Image.Height)
{
maxDimPix = Image.Width;
}
else
{
maxDimPix = Image.Height;
}
sourceRes = Convert.ToInt32(Image.HorizontalResolution);
maxDimInch = Convert.ToInt32(maxDimPix / sourceRes);
//Assign size red factor based on max dimension of image (inches)
if (maxDimInch >= 17)
{
redFactor = 0.45;
}
else if (maxDimInch < 17 && maxDimInch >= 11)
{
redFactor = 0.65;
}
else if (maxDimInch < 11 && maxDimInch >= 8)
{
redFactor = 0.85;
}
else//smaller than 8" dont reduce dimensions
{
redFactor = 1;
}
destWidth = Convert.ToInt32(Image.Width * redFactor);
destHeight = Convert.ToInt32(Image.Height * redFactor);
Bitmap bm = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
bm.SetResolution(Image.HorizontalResolution, Image.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bm);
grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(Image,
new Rectangle(0, 0, destWidth, destHeight),
new Rectangle(0, 0, Image.Width, Image.Height),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bm;
}
If I'm reading the code right, your i variable is zero every time through the loop.
It is hard to diagnose exactly what is wrong, I would recommend that you use using statements to ensure that your instances are getting disposed of properly, but it looks like they are.
I originally thought it might be an issue with the ScaleImage. So I tried a different resize function (C# GDI+ Image Resize Function) and it worked, but i is always set to zero at beginning of each loop. Once you move i's initialization outside of the loop your scale method works as well.
private void MethodName()
{
string fileReducedDimName = #"c:\pics";
int i = 0;
foreach (string file in Directory.GetFiles(fileReducedDimName, "*.jpg"))
{
//if the file dimensions are big, scale the file down
using (Image image = Image.FromFile(file))
{
using (Bitmap bm = ScaleImage(image))
{
bm.Save(fileReducedDimName + #"\" + i.ToString() + ".jpg", ImageFormat.Jpeg);//error occurs here
//this is all redundant code - do not need
//Array.Clear(photoByte, 0, photoByte.Length);
//bm.Dispose();
}
}
//ResizeImage(file, 50, 50, fileReducedDimName +#"\" + i.ToString()+".jpg");
i++;
}
}
I am using the following method to take screenshots and noticed that all of the screenshot images are not capturing the full window but instead cropping the window. For example I will get a .jpg where I cannot see the entire webpage that is visible on the screen. I suspect that this happens when certain elements are not visible in the DOM and therefore not included in the screenshot. Is this expected behavior? If this is expected, is there a way to program the driver to take a full screen capture with the Selenium 32 bit Internet Explorer Driver consistently? Here is the method I am calling to take the screenshots.
public static void TakeScreenshot(IWebDriver driver, string saveLocation)
{
ITakesScreenshot ssdriver = driver as ITakesScreenshot;
Screenshot screenshot = ssdriver.GetScreenshot();
screenshot.SaveAsFile(saveLocation, ImageFormat.png);
}
Indeed, Richard's answer will work to take a screenshot of the entire current desktop area - if that is what you are after, it will work. If you are actually after having a specific application (e.g. Internet Explorer) that is not 'maximized' while using Selenium, then you might need to take a different approach. Consider forcing the application to be maximized and maybe even have it get focus before taking the screenshot using Richard's method above - or use the Selenium's ITakesScreenshot interface ...
In order to use the System.Windows.Forms namespace in a Console application, you will need to "Add Reference..." to the project. In the Solution Explorer, right-click on "References" and select "Add Reference..."; scroll to System.Windows.Forms, check it and click Okay. After doing that, you will be able to type "using System.Windows.Forms;" at the top of your class file.
This is what I use for capturing the entire screen:
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(saveLocation, System.Drawing.Imaging.ImageFormat.Png);
}
the resolution:
Detect if the web page can be display on current browser
If current window screenshot is enough then use screenshot of current browser window
If the current page include scroll bar, then take screen shot of each window by scroll the page accordingly, and cut the screenshot to combine all screenshot together
Put code for whole page screenshot:
using System.Linq;
using System.Threading;
using OpenQA.Selenium;
using DotRez.Utilities.WebDriver;
using System.Drawing;
using System.Drawing.Imaging;
// decide take full screenshot and take current window screenshot according to the height
public static void TakeSnapshot()
{
IJavaScriptExecutor js = Driver as IJavaScriptExecutor;
var fileName = ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier() + DateTime.Now.ToString("HH_mm_ss") + "JS" + ".png";
var fileLocation = Path.Combine(Configuration.SCREEN_SHOT_LOCATION, fileName);
Image finalImage;
// get the full page height and current browser height
string getCurrentBrowserSizeJS =
#"
window.browserHeight = (window.innerHeight || document.body.clientHeight);
window.headerHeight= document.getElementById('site-header').clientHeight;;
window.fullPageHeight = document.body.scrollHeight;
";
js.ExecuteScript(getCurrentBrowserSizeJS);
// * This is async operation. So we have to wait until it is done.
string getSizeHeightJS = #"return window.browserHeight;";
int contentHeight = 0;
while (contentHeight == 0)
{
contentHeight = Convert.ToInt32(js.ExecuteScript(getSizeHeightJS));
if (contentHeight == 0) System.Threading.Thread.Sleep(10);
}
string getContentHeightJS = #"return window.headerHeight;";
int siteHeaderHeight = 0;
while (siteHeaderHeight == 0)
{
siteHeaderHeight = Convert.ToInt32(js.ExecuteScript(getContentHeightJS));
if (siteHeaderHeight == 0) System.Threading.Thread.Sleep(10);
}
string getFullPageHeightJS = #"return window.fullPageHeight";
int fullPageHeight = 0;
while (fullPageHeight == 0)
{
fullPageHeight = Convert.ToInt32(js.ExecuteScript(getFullPageHeightJS));
if (fullPageHeight == 0) System.Threading.Thread.Sleep(10);
}
if (contentHeight == fullPageHeight)
{
TakeSnapshotCurrentPage();
}
else
{
int scollEachHeight = contentHeight - siteHeaderHeight;
int shadowAndBorder = 3;
int scollCount = 0;
int existsIf = (fullPageHeight - siteHeaderHeight) % scollEachHeight;
bool cutIf = true;
if (existsIf == 0)
{
scollCount = (fullPageHeight - siteHeaderHeight) / scollEachHeight;
cutIf = false;
}
else
{
scollCount = (fullPageHeight - siteHeaderHeight) / scollEachHeight + 1;
cutIf = true;
}
// back to top start screenshot
string scollToTopJS = "window.scrollTo(0, 0)";
js.ExecuteScript(scollToTopJS);
Byte[] imageBaseContent = ((ITakesScreenshot)Driver).GetScreenshot().AsByteArray;
Image imageBase;
using (var ms = new MemoryStream(imageBaseContent))
{
imageBase = Image.FromStream(ms);
}
finalImage = imageBase;
string scrollBar = #"window.scrollBy(0, window.browserHeight-window.headerHeight);";
for (int count = 1; count < scollCount; count++)
{
js.ExecuteScript(scrollBar);
Thread.Sleep(500);
Byte[] imageContentAdd = ((ITakesScreenshot)Driver).GetScreenshot().AsByteArray;
Image imageAdd;
using (var msAdd = new MemoryStream(imageContentAdd))
{
imageAdd = Image.FromStream(msAdd);
}
imageAdd.Save(fileLocation, ImageFormat.Png);
Bitmap source = new Bitmap(imageAdd);
int a = imageAdd.Width;
int b = imageAdd.Height - siteHeaderHeight;
PixelFormat c = source.PixelFormat;
// cut the last screen shot if last screesshot override with sencond last one
if ((count == (scollCount - 1)) && cutIf)
{
Bitmap imageAddLastCut =
source.Clone(new System.Drawing.Rectangle(0, contentHeight - existsIf, imageAdd.Width, existsIf), source.PixelFormat);
finalImage = combineImages(finalImage, imageAddLastCut);
source.Dispose();
imageAddLastCut.Dispose();
}
//cut the site header from screenshot
else
{
Bitmap imageAddCutHeader =
source.Clone(new System.Drawing.Rectangle(0, (siteHeaderHeight + shadowAndBorder), imageAdd.Width, (imageAdd.Height - siteHeaderHeight - shadowAndBorder)), source.PixelFormat);
finalImage = combineImages(finalImage, imageAddCutHeader);
source.Dispose();
imageAddCutHeader.Dispose();
}
imageAdd.Dispose();
}
finalImage.Save(fileLocation, ImageFormat.Png);
imageBase.Dispose();
finalImage.Dispose();
}
}
//combine two pictures
public static Bitmap combineImages(Image image1, Image image2)
{
Bitmap bitmap = new Bitmap(image1.Width, image1.Height + image2.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(image1, 0, 0);
g.DrawImage(image2, 0, image1.Height);
}
return bitmap;
}
// take current window screenshot
private static void TakeSnapshotCurrentPage()
{
try
{
var screenshot = ((ITakesScreenshot)Driver).GetScreenshot();
var urlStr = Driver.Url;
var fileName = ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier() + DateTime.Now.ToString("HH_mm_ss") + ".png";
var fileLocation = Path.Combine(Configuration.SCREEN_SHOT_LOCATION, fileName);
if (!Directory.Exists(Configuration.SCREEN_SHOT_LOCATION))
{
Directory.CreateDirectory(Configuration.SCREEN_SHOT_LOCATION);
}
screenshot.SaveAsFile(fileLocation, ScreenshotImageFormat.Png);
Console.WriteLine(urlStr);
Console.WriteLine("SCREENSHOT[{0}]SCREENSHOT", Path.Combine("Screenshots", fileName));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}