Showing posts with label text. Show all posts
Showing posts with label text. Show all posts

Thursday, November 17, 2016

Modify Clipboard content using Java

You can modify the text or images in clipboard using Java.

Software Features:

1) It can place any custom text on your clipboard
2) It can place any custom image to your clipboard

Language:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/Clipboard/ModifyClipboard

Program:

Main method:
      public static void main(String[] args) throws Exception {  
           Toolkit toolkit = Toolkit.getDefaultToolkit();  
           Clipboard clipboard = toolkit.getSystemClipboard();  
           Scanner s=new Scanner(System.in);  
           System.out.println("Press 1 to copy text and 2 for copying image to clipboard");  
           int ch=s.nextInt();  
           if(ch==1)  
           {  
           setText(clipboard,"Text placed to clipboard by Java");  
           System.out.println("If you press Ctrl+v then you will see the text \"Text placed to clipboard by Java\"");  
           }  
           else if(ch==2)  
           {  
                Robot robot = new Robot();  
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
          Rectangle screen = new Rectangle( screenSize );  
          BufferedImage image = robot.createScreenCapture( screen );  
                setImageFromClipboard(clipboard, image);  
                System.out.println("Copied your desktop screenshot to your clipboard.");  
                System.out.println("Press Ctrl+v on paint and you will see your screenshot");  
           }  
      }  


How it works:
1) We access the clipboard object by using Toolkit.getDefaultToolkit().getSystemClipboard()
2) We ask user if he want to copy text or image on clipboard
3) If user choose to copy text, it calls setText method which will copy the text "Text placed to clipboard by Java" to your clipboard
4) If user choose to copy image then we take screenshot of the screen and call setImageFromClipboard method passing the image we took

setText method:
      public static void setText(Clipboard clipboard, String text)  
      {  
           StringSelection selection = new StringSelection(text);  
           clipboard.setContents(selection, selection);  
      }  


How it works:
1) Make object of StringSelection with the text to be copiedFile
2) we use setContent to set the text in the clipboard

setImageFromClipboard method:
      public static void setImageFromClipboard(Clipboard clipboard, BufferedImage image)  
                throws Exception  
                {  
     ImageSelection imgSel = new ImageSelection(image);  
     clipboard.setContents(imgSel, null );  
                }  


How it works:
1) We created a class ImageSelection since we dont have it predefined.
2) We make an object of ImageSelection and pass the image to be copied
3) we use setcontent and pass the ImageSelection object which copies the image to clipboard

ImageSelection class:
 class ImageSelection implements Transferable  
 {  
  private Image image;  
  public ImageSelection(Image image)  
  {  
   this.image = image;  
  }  
  // Returns supported flavors  
  public DataFlavor[] getTransferDataFlavors()  
  {  
   return new DataFlavor[] { DataFlavor.imageFlavor };  
  }  
  // Returns true if flavor is supported  
  public boolean isDataFlavorSupported(DataFlavor flavor)  
  {  
   return DataFlavor.imageFlavor.equals(flavor);  
  }  
  // Returns image  
  public Object getTransferData(DataFlavor flavor)  
    throws UnsupportedFlavorException, IOException  
  {  
   if (!DataFlavor.imageFlavor.equals(flavor))  
   {  
    throw new UnsupportedFlavorException(flavor);  
   }  
   return image;  
  }  

How it works:
1) This class implements Transferable so that we can use it to set image in clipboard
2) The contructor sets the image passed by user
3) getTransferData returns the image which will be placed in clipboard

Sample Output:
Press 1 to copy text and 2 for copying image to clipboard
2
Copied your desktop screenshot to your clipboard.
Press Ctrl+v on paint and you will see your screenshot

Hope it helps :)

Wednesday, November 16, 2016

Access Clipboard content using Java

You can access the text or images in clipboard using Java.

Software Features:

1) On copying any text, it gets placed in clipboard. This program can retrieve the text from clipboard
2) On using print screen, the image gets stored in clipboard. This program can retrieve the image from clipboard
3) When you copy file in windows, the file path get stored in clipboard. This program can retrieve the file path from clipboard and then copy the file to current directory.

Language:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/Clipboard/AccessClipboard

Terms Used:
Current directory: Current directory in this post refer to the path from where you are running the program

Program:

Main method:
      public static void main(String[] args) throws Exception {  
           Toolkit toolkit = Toolkit.getDefaultToolkit();  
           Clipboard clipboard = toolkit.getSystemClipboard();  
           if (clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor))   
           {  
           getCopiedFile(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))   
           {  
           getText(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor))   
           {  
           getImageFromClipboard(clipboard);  
           }  
      }  


How it works:
1) We access the clipboard object by using Toolkit.getDefaultToolkit().getSystemClipboard()
2) Now we check what data is present in clipboard by calling isDataFlavorAvailable(DataFlavor)
3) If copied image is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor) will return true else false. If true, we call getCopiedFile(clipboard) which shows the name of all files which user copied and saves the copied file at current directory.
4) If text is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) will return true else false. If true then we call getText(clipboard) which retrieves the text from clipboard and prints the same
5) If print screen image is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor) return true else false. If true, we call getImageFromClipboard(clipboard) which retrieves the print screen image and saves it to your current directory

getCopiedFile method:
      public static Object getCopiedFile(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           Object result = clipboard.getData(DataFlavor.javaFileListFlavor);  
     List files = (List) result;  
     for (int i = 0; i < files.size(); i++) {  
       File file = (File) files.get(i);  
       File destFile=new File(file.getName());  
       copyFileUsingStream(file, destFile);  
       System.out.println("Copied file "+file.getName()+" to "+destFile.getAbsolutePath());  
     }  
           return result;  
      }  


How it works:
1) This method is called to retrieve the copied image and save those.
2) To explain we will take an example. Assume user copied c:\1.jpg & c:\2.jpg
3) Clipboard will now have 2 entries which is c:\1.jpg and c:\2.jpg
4) clipboard.getData(DataFlavor.javaFileListFlavor) will retrieve both the entries from clipboard in form of List<File>
5) We iterate through each entry of List<File>
6) For each File found we will copy it to the current directory. So in 1st iteration we will copy 1.jpg to the current directory & in next iteration it would copy 2.jpg to current directory.

getImageFromClipboard method:
      public static Image getImageFromClipboard(Clipboard clipboard)  
                throws Exception  
                {  
                 Transferable transferable = clipboard.getContents(null);  
                 Image img=(Image) transferable.getTransferData(DataFlavor.imageFlavor);  
                     if(img!=null)  
                     {  
                          counter++;  
                          BufferedImage buffered = (BufferedImage) img;  
                          ImageIO.write(buffered, "jpg", new File("copiedFile"+counter+".jpg"));  
                          System.out.println("Saved the clipboard image as copiedFile"+counter+".jpg");  
                     }  
                     return img;  
                }  


How it works:
1) Assume user press print screen on a page. Now the print screen image gets saved to clipboard.
2) clipboard.getContents(null).getTransferData(DataFlavor.imageFlavor) gets the image from the clipboard
3) We cast the Image to BufferedImage and then use ImageIO to write the image to a file which gets saved in current directory

getText method:
      public static String getText(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           String result = (String) clipboard.getData(DataFlavor.stringFlavor);  
           System.out.println("String from Clipboard:" + result);  
           return result;  
      }  


How it works:
1) Assume user copies a text and now the text is present in clipboard
2) clipboard.getData(DataFlavor.stringFlavor) gets the text from the clipboard and then we print it

copyFileUsingStream method:
      private static void copyFileUsingStream(File source, File dest) throws IOException {  
        InputStream is = null;  
        OutputStream os = null;  
        try {  
          is = new FileInputStream(source);  
          os = new FileOutputStream(dest);  
          byte[] buffer = new byte[1024];  
          int length;  
          while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
          }  
        } finally {  
          is.close();  
          os.close();  
        }  
      }  


How it works:
1) This method copies files from source to destination.

Sample Output:
Copied file 2.png to C:\Users\anurag\workspace\cooltrickshome\2.png
Copied file oranges-1117628_640.jpg to C:\Users\anurag\workspace\cooltrickshome\oranges-1117628_640.jpg

Full Program:
 package com.cooltrickshome;  
 import java.awt.Image;  
 import java.awt.Toolkit;  
 import java.awt.datatransfer.Clipboard;  
 import java.awt.datatransfer.DataFlavor;  
 import java.awt.datatransfer.Transferable;  
 import java.awt.datatransfer.UnsupportedFlavorException;  
 import java.awt.image.BufferedImage;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.OutputStream;  
 import java.util.ArrayList;  
 import java.util.List;  
 import javax.imageio.ImageIO;  
 public class AccessClipboard {  
      /**  
       * @param args  
       * @throws Exception   
       */  
      static int counter=0;  
      public static void main(String[] args) throws Exception {  
           Toolkit toolkit = Toolkit.getDefaultToolkit();  
           Clipboard clipboard = toolkit.getSystemClipboard();  
           if (clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor))   
           {  
           getCopiedFile(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))   
           {  
           getText(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor))   
           {  
           getImageFromClipboard(clipboard);  
           }  
      }  
      public static Object getCopiedFile(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           Object result = clipboard.getData(DataFlavor.javaFileListFlavor);  
     List files = (List) result;  
     for (int i = 0; i < files.size(); i++) {  
       File file = (File) files.get(i);  
       File destFile=new File(file.getName());  
       copyFileUsingStream(file, destFile);  
       System.out.println("Copied file "+file.getName()+" to "+destFile.getAbsolutePath());  
     }  
           return result;  
      }  
      public static Image getImageFromClipboard(Clipboard clipboard)  
                throws Exception  
                {  
                 Transferable transferable = clipboard.getContents(null);  
                 Image img=(Image) transferable.getTransferData(DataFlavor.imageFlavor);  
                     if(img!=null)  
                     {  
                          counter++;  
                          BufferedImage buffered = (BufferedImage) img;  
                          ImageIO.write(buffered, "jpg", new File("copiedFile"+counter+".jpg"));  
                          System.out.println("Saved the clipboard image as copiedFile"+counter+".jpg");  
                     }  
                     return img;  
                }  
      public static String getText(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           String result = (String) clipboard.getData(DataFlavor.stringFlavor);  
           System.out.println("String from Clipboard:" + result);  
           return result;  
      }  
      private static void copyFileUsingStream(File source, File dest) throws IOException {  
        InputStream is = null;  
        OutputStream os = null;  
        try {  
          is = new FileInputStream(source);  
          os = new FileOutputStream(dest);  
          byte[] buffer = new byte[1024];  
          int length;  
          while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
          }  
        } finally {  
          is.close();  
          os.close();  
        }  
      }  
 }  

Hope it helps :)