How do I copy an image to the clipboard in Selenium? - c#

I am writing a test and the functionality I need to replicate is essentially saving a image to the clipboard and paste it later on. I am using Selenium WebDriver v3.11.1.
I have attempted using ContextClick to copy an image in many various ways and it never quite did what I wanted for example:
Actions rightClickAction = new Actions(driver);
rightClickAction.MoveToElement(logo).ContextClick(logo).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.Enter).Build().Perform();
But the arrow down/enter never worked because it didn't focus on the right click menu. So then I found this bug https://bugs.chromium.org/p/chromedriver/issues/detail?id=1003 which makes me think that I can't use context click to copy an image. I also, couldn't just 'ctrl+c' the image.
I then learned that I could Clipboard which I couldn't get to set an image from my directory:
Clipboard.SetImage(Image.FromFile("C://Image.png"));
I then tried taking a screenshot as done here: C# Selenium - How do you take a screenshot in Visual Studio 2015 and that didn't work with either. Trying to save the screenshot file and add it to the 'clipboard' got messy.
I have also tried grabbing an image from a page by getting a base64 string of the image with JavaScript that is executed by webdriver, then saving the base64 string of the image to a file, which I found here: Using selenium to save images from page
This also got messy and I wasn't sure how to then save it to the clipboard.
So, how can I save an image to my clipboard?

You can try something similar to this:
driver.get("https://stackoverflow.com/");
WebElement element = driver.findElement(By.xpath("//span[(text()='Stack Overflow') and #class='-img _glyph']"));
WrapsDriver wrapsDriver = (WrapsDriver) element;
File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height, element.getSize().height, element.getSize().width);
Point location = element.getLocation();
BufferedImage bufferedImage = ImageIO.read(screenshot);
BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
ImageIO.write(destImage, "png", screenshot);
File file = new File("C:\\tmp\\123.png");
FileUtils.copyFile(screenshot, file);
Let me know if it works for you

Related

Selenium - Uploading image to website when input doesn't exist in HTML code and web uses SelectFileDialog

I have this problem for I can't find proper solution.
On website trovo.live I'm trying to change profile picture with code. There is 'Upload' button, which opens SelectFileDialog.
When I try to find input tag via document.getElementsByTagName("input") it doesn't find any input for uploading. (So I can't just do element.SendKeys() )
It works this way, when I select file in dialog then website converts it into data URI and set it as < img > src + it sets style = transform: matrix(values params)
So I found this solution that I convert image into data URI and set it as src parameter like website do it. Also I calculate matrix parameter values.
My problem is when I click save button later, website for some reason resets my css style and then picture is saved with bad positioning
After I change src by code (transform style remains from previous avatar)
This is how it looks when I upload manualy by Upload button or I can matrix() values
But when I click save button, it saves like that first picture, like it wouldn't count in my matrix() values. Can I somehow get into save button function and force in my matrix() edit? Or simulate Upload function without pressing button?
Or how can I handle selectFileDialog in selenium when
No < input > in HTML code
I can't use System.Windows.Forms.SendKeys.SendWait(path);
I also tried to use AutoItX, but I had some problems with their library in my project and I would like to handle it without libraries if possible.
Thank you very much for all answers :)
**edit
I found .js file which contains code for it, but I have no idea how to call for example method for resizing on method image code for javascript

Button image content wont show except after step by step debug

I'm at a loss here...
Just trying to get an image showing on a button from codebehind. The image is being fed by the user in a dialog and is copied in the executable folder.
Image buttonImage = new Image();
buttonImage.Source = new BitmapImage(new Uri(Name + ".png", UriKind.Relative));
buttonImage.Height = 100;
Content = buttonImage;
It actually does work but only when stepping with the debugger. The code abode is from within my own Button control in a desperate attempt to try a slightly different way and see if the result would be different.
From what I've found, most people recommend setting Button Content Templates and use databinding from there, but it's not an option here.
Any idea why that wouldn't show up properly?
Thanks for any help you can give.
EDIT: this and the answer links have been studied to no avail
EDIT2: It's really when I'm changing a value within the Image Control at runtime that the image shows up afterward. I obviously tried to put the option changed directly into the code but it didn't work... (changed the stretch mode to be sure it wasn't a scale issue)

PDF Clown does not render text

I use PDF Clown to create PDF files containing text and different shapes. Saving the files brings the desired result. But when I print the pages or render them to bitmaps, only the shapes are visible and the text elements are missing.
I tried already different versions of the library with multiple files, always getting the same result.
Maybe someone can give me a hint on this issue.
EDIT:
This is a simplified form of the source code I use (with same result as described above; see the image at the end):
File file = new File();
Document document = file.Document;
document.PageSize = PageFormat.GetSize(PageFormat.SizeEnum.A4, PageFormat.OrientationEnum.Portrait);
Page page = new Page(document);
document.Pages.Add(page);
PrimitiveComposer composer = new PrimitiveComposer(page);
//draw a rectangle
composer.SetFillColor(DeviceRGBColor.Get(System.Drawing.Color.LightSalmon));
composer.DrawRectangle(new RectangleF(30, 42, 300, 32));
composer.Fill();
//draw some text
composer.SetFillColor(DeviceRGBColor.Get(System.Drawing.Color.Black));
composer.SetFont(new StandardType1Font(document, StandardType1Font.FamilyEnum.Courier, true, false), 32);
composer.ShowText("Hello World!", new PointF(32, 48));
composer.Flush();
//save the file
file.Save(#"..\document.pdf", SerializationModeEnum.Standard);
//and print it
Renderer renderer = new Renderer();
renderer.Print(file.Document, false);
Result of the above code (the printed version was created with virtual printer Adobe PDF; also tested with XPS Document Writer):
(I don't have enough points to add a comment so I put this comment as an answer.) If you look in the source for the RenderingSample class, you will see this comment:
This sample demonstrates how to render a PDF page as a raster image.
Note: rendering is currently in pre-alpha stage; therefore this sample is
nothing but an initial stub (no assumption to work!).
I don't think Stephano Chizzolini got around to finishing it.
There is another NuGet download, PDFClown.Net version 2.0.0, by Matthieu. It has tags for PDF-To-Image, Rasterizer and PDF, but I have not been able to get it to work either. I cannot find documentation for it. Inspection of the properties for the downloaded NuGET assembly shows version 0.1.2.0 instead of 2.0.0.

Loading PictureBox Image from resource file with path (Part 3)

I understand that this question has been asked (and answered) before. However, none of the solutions are working for me.
Below is a screen capture of all the relevant pieces of the puzzle:
Screen capture http://dinosaur-island.com/PlantPictureBoxScreenCap.jpg
As you can see there are numerous bitmaps of plants loaded as resources into the Images folder. There is a form with a picturebox named "PlantPicture". There is string, which I know has a good path (because I've checked it in the debugger):
PicPath = PicPath+".bmp";
Screen capture http://dinosaur-island.com/PlantDebugger.jpg
I've tried numerous ways of loading, casting, etc., etc.
The path should be something like: "Images\a.bmp". (Note the lack of a leading slash, and the slashes being back slashes.)
And then:
pictureBox1.Image = Image.FromFile(#"Images\a.bmp");
I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
It depends on your file path. For me, the current directory was [project]\bin\Debug, so I had to move to the parent folder twice.
Image image = Image.FromFile(#"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;
To find your current directory, you can make a dummy label called label2 and write this:
this.label2.Text = System.IO.Directory.GetCurrentDirectory();
The accepted answer has major drawback!
If you loaded your image that way your PictureBox will lock the image,so if you try to do any future operations on that image,you will get error message image used in another application!
This article show solution in VB
and This is C# implementation
FileStream fs = new System.IO.FileStream(#"Images\a.bmp", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(fs);
fs.Close();
Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.
Your PicPath is a relative path that is converted into an absolute path at some time while loading the image.
Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

how to resize a picture programatically and add it to the web site

Hi there
I am working with visual web developer and would a) like to know how I could programatcally add a picture to the website, instead of going to Website and then add existing item. The idea I have is to upload the picture using the file upload control but then I want to have it added so that it can be accessed using a gridview.
b)I would also like to know how to size the picture using C# code obviously so that is displayed at the correct size.
best regards
arian
here is a full project with source code to manipulate images, including resize.
http://www.codeproject.com/KB/web-image/ASPImaging1.aspx
And a sample code only for resize
http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx
You can use GetThumbnailImage to easily create a smaller verson of the uploaded image. The code looks something like (it's free typed without a compiler, so there may be some errors):
System.Drawing.Image pic = new System.Drawing.Bitmap(sourceFilename);
System.Drawing.Image thumb = pic.GetThumbnailImage(targetXSize,targetYSize,
new System.Drawing.Image.GetThumbnailImageAbort(this.GetThumbnailImageAbort),
IntPtr.Zero);
thumb.Save(thumbPathName);
I believe the Image implements IDisposable, so you need to remember to Dispose of them when you're done.
The abort parameter can be a function that simply does this (can't remember off the top of my head when it gets called):
bool GetThumbnailImageAbort() {
return false;
}

Categories

Resources