How to simulate Print screen button using selenium webdriver in Java - java

How to simulate Print screen button using selenium web driver in Java
Regards,
Vignesh

selenium doesn't support it, only web page shots. However you can use Robot to do it
try {
String format = "jpg";
String fileName = printScreen." + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(fileName));
} catch (AWTException | IOException ex) {
System.err.println(ex);
}
And in C#
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
bitmap.Save(#"C:\ScreenShots\printScreen.jpg", ImageFormat.Jpeg);

Related

Java OpenCV save video file

I would like to save a file (avi) of some frames (in this case, 600) from my webcam using java opencv, but i have no idea how to do that, the code below gives me the avi file specified but with size 0, no frames inside whatsover, also in the directory i have those 600 frames in jpeg's.
It's important to use java for that, no python.
Mat frame = new Mat();
VideoWriter writer = new VideoWriter("c:/opencv/vid.avi", VideoWriter.fourcc('X','2','6','4'), 30 ,frame.size(), true);
videoCapture = new VideoCapture();
videoCapture.open(0);
videoCapture.set(Videoio.CAP_PROP_FRAME_WIDTH, 1280);
videoCapture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 720);
while (true){
videoCapture.read(frame);
if (!frame.empty())
break;
}
int frameNo = 0;
while (frameNo < 600){
videoCapture.read(frame);
writer.write(frame);
Imgcodecs imageCodecs = new Imgcodecs();
String file = "c:/opencv/i" + frameNo + ".jpg";
Imgcodecs.imwrite(file,frame);
frameNo++;
}
videoCapture.release(); // release device
You didn't mention which openCV version are you using, I use OpenCV-3.4.2
AVI container use DIVX codec reference: https://wiki.videolan.org/DivX/
I modify a bit your code:
Mat frame = new Mat();
VideoWriter writer = new VideoWriter("c:/opencv/vid.avi", VideoWriter.fourcc('D', 'I', 'V', 'X'), 30, new Size(videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH), videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT)));
while(runnable)
{
if(videoCapture.grab())
{
try
{
//Decodes and returns the grabbed video frame.
videoCapture.retrieve(frame);
//encode to .jpg the frame to a MatOfByte
Imgcodecs.imencode(".jpg", frame, mem);
//read into an Image
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
//Draw image to a Jpanel
BufferedImage buff = (BufferedImage) im;
Graphics g = jPanel1.getGraphics();
g.drawImage(buff, 0, 0, getWidth(), getHeight(), 0, 0, buff.getWidth(), buff.getHeight(), null);
//record the frame
writer.write(frame);
}
catch(Exception ex)
{
System.out.println("Error");
ex.printStackTrace();
}
}
}
videoCapture.release(); // release device

How to compress and resize image from a Rich Text

I am inserting image in using this
var readFileIntoDataUrl = function (fileInfo) {
var loader = $.Deferred(),
fReader = new FileReader();
fReader.onload = function (e) {
loader.resolve(e.target.result);
};
fReader.onerror = loader.reject;
fReader.onprogress = loader.notify;
fReader.readAsDataURL(fileInfo);
return loader.promise();
};
$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
execCommand('insertimage', dataUrl);
}).fail(function (e) {
options.fileUploadError("file-reader", e);
});
Let say i added a text Hello World and added a image. Now when i take $("#editor").html() it shows something like below
Here is a sample source of a image+text
Hello World!
img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgA
BAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAA
AQAAAGAAAAABUGFpbnQuTkVUIHYzLjUuOAAA/9sAQwAHBQUGBQQHBgUGCAcHCAoRCwoJCQoVDxAMERgV
[... more base64 data here....]
Now here i have both text+image So both on server side and client side i want to resize & compress image
So that no one can insert image > 5MP and also keep a rich text with resize image in my db
This is how you can do it on the server side (Java):
String imageData = "Hello World! img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoR...";
//Image data starting point
int startIndex = imageData.indexOf(";base64,") + ";base64,".length();
//keep only the image data
imageData = imageData.substring(startIndex, imageData.length());
//convert the image data String to a byte[]
byte[] dta = DatatypeConverter.parseBase64Binary(imageData);
try (InputStream in = new ByteArrayInputStream(dta);) {
BufferedImage fullSize = ImageIO.read(in);
// Create a new image half the size of the original image
BufferedImage resized = new BufferedImage(fullSize.getWidth() / 2, fullSize.getHeight() / 2, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = (Graphics2D) resized.getGraphics();
g2.drawImage(fullSize, 0, 0, resized.getWidth(), resized.getHeight(), 0, 0, fullSize.getWidth(), fullSize.getHeight(), null);
g2.dispose();
} catch (IOException e) {
e.printStackTrace();
}
As for the JavaScript part you can use a canvas, size the canvas to the dimension that you want, draw your image on it and use the toDataURL method to convert the image to a String

Automatically capture clip board data and save it into a file

Capture a image from the clipboard whenever Print screen is pressed and save it in a file (.doc) using java
Main aim is to copy the data from the clipboard and automatically save it into local disk without going to the desired program (i.e MS Word)- click new - pressing (Ctrl+V) to paste and save it with a name.
The code should perform all of the above three steps automatically.
My Source Code
public class CaptureScreenShot {
private static String DIR ="C:\\QUIS\\";
private static JTextField txtDocNumber;
public static void main(String[] args) throws Exception{
txtDocNumber = new JTextField();
Robot robot = new Robot();
Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int width = (int) d.getWidth();
int height = (int) d.getHeight();
robot.delay(5000);
Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
height));
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
String fileNameToSaveTo = "C:/QUIS/screenCapture_" + createTimeStampStr() + ".PNG";
String newFile = "C:/QUIS/x" + ".org";
File newFilee = new File(newFile);
writeImage(bi, fileNameToSaveTo, "PNG");
System.out.println("Screen Captured Successfully and Saved to:\n"+fileNameToSaveTo);
Desktop desktop = Desktop.getDesktop();
writeImage(bi, newFile, "org");
desktop.open(newFilee);
}
public static int writeImage(BufferedImage img, String fileLocation,
String extension) {
try {
BufferedImage bi = img;
File outputfile = new File(fileLocation);
ImageIO.write(bi, extension, outputfile);
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public static String createTimeStampStr() throws Exception {
Calendar mycalendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
String timeStamp = formatter.format(mycalendar.getTime());
return timeStamp;
}
}
If you are not particular about a java code, you could use some screen capture tool instead. Snagit is a good tool. You could find it on http://www.techsmith.com/snagit.html
Try this sample code, according to your question it will copy contents from clipboard and will generate image file
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);
//file that we'll save to disk.
File file = new File("image.jpg");
//class to write image to disk. You specify the image to be saved, its type,
// and then the file in which to write the image data.
ImageIO.write(image, "jpg", file);
}

How to print conent of a JFrame by printer

I would like to print the content of a JFrame/JPanel by printer how to do it? Could sb give me an example of code? I do not understand official tutorial.
EDIT:
I thought it is clear. I do not want to print it to file then print it manually. I want to use java to do this.
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
this.paint(g);
g.dispose();
// File to save output Image
File imageOut = new File("screenshot.png");
try {
ImageIO.write(image, "png", imageOut);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
with this as a JFrame

Java file operations after opening image with ImageIO

I am working with Java and combine two images. I save the combined image and want to delete the overlay, but it seems there are still streams open. And i don't know which and how to close them.
f_overlay and f_image are both Files.
// load source images
BufferedImage image = null;
BufferedImage overlay = null;
try {
log.debug(f_image.getAbsolutePath());
log.debug(f_overlay.getAbsolutePath());
image = ImageIO.read(f_image);
overlay = ImageIO.read(f_overlay);
} catch (IOException e) {
log.error(e.getMessage());
}
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// paint both images, preserving the alpha channels
Graphics g = combined.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(overlay, 0, 0, null);
// Save as new image
try {
ImageIO.write(combined, "PNG", f_image);
} catch (IOException e) {
log.error(e.getMessage());
}
// we can delete the overlay now
log.debug("Delete overlay: " + f_overlay.delete());
Are there any suggestions?
I can't see anything wrong in your code.
However, I would only delete the file f_overlay if the reading was successful. Important, after you call delete() on the file object, you must not use the object for anything else, so best is to assign f_overlay=null
boolean state = f_overlay.delete();
f_overlay=null;
log.debug("Delete ... "+state);

Categories

Resources