Command-line Utility to Save content of clipboard as BMP or JPG file

Posted on 2006-04-01
Last Modified: 2013-12-03
I'm looking for a lightweight command-line utility that will save the content of the clipboard as a BMP file, or a JPG file where the quality setting of the JPG is either lossless or can be specified on the command-line. The clipboard freeware category seems rather popular, so a tool like this may already exist, in which case a link to download the utility would be sufficient. Otherwise, I would guess that a coded solution in .net or vbscript utilizing an open source component would be fairly straightforward to implement. The intended platform is windows 2003.

The specific application of this utility would be as follows. Using a script, I want to open Excel, copy a range of cells (including any emedded charts) to the clipboard, then save the clipboard as a graphics file for inclusion on a webpage. All these steps need to be done non-interactively. Since I'm not sure about the nature of the data saved to the clipboard when you execute a copy in Excel, a second step where the copied content is pasted-special as a bitmap object, and then that bitmap is copied to the clipboard - this may be even more straightforward. The solution should be more general than this example (i.e. the contents of the clipboard may come from other sources besides Excel).
Question by:zacbell
    LVL 86

    Expert Comment


    Author Comment

    I checked that site before posting this question, but have not been able to access the site (Cannot find server or page). Any ideas or know if the binaries are cached somewhere?
    LVL 86

    Expert Comment

    Oh great :-(

    I have that archive on my office machine, but I am not sure whether it would be legal to distribute it, and can't check the license since - err, well...

    But, since that site used to work for me recently, that might also just be a momentary DNS glitch.

    Author Comment

    Haven't been able to access the site yet. However, I checked the Google-cached version of the site, and I'm not sure your proposed utility provides the feature I need (of course, the cached description of the utility may not describe all the functionality). Perhaps the latest version (2.2) allows the reverse of the feature described above - i.e. copy clipboard to bmp rather than vice versa.

    CLIP v2.2 - Store a text file in the Windows clipboard
    One of my many jobs is answering questions from other programmers. And I often find the need to write some small code samples, test them, and then send them out as email. I found it annoying to load my source examples into an editor just to get them into the clipboard. So I wrote CLIP to take any filename passed on the command line and the contents of the text file into the clipboard. Version 2.1 now allows you to copy bitmap (.BMP) files to the clipboard.


    Accepted Solution

    I decided I didn't like the idea of spending too much time searching for an existing implementation, when I suspected that the implementation should be rather straightforward. I wrote the following source that does precisely what I was looking for, although it does hard-code a cropping action that seems to be required to get rid of some borders that Excel adds the the copied bitmap. If I do end up using other copy sources as I suggested in the prompt, I could parameterize this behavior.

    Imports System.Windows.Forms
    Imports System.Drawing
    Imports System.Drawing.Imaging

    Module ClipOut

        Sub Main(ByVal args As String())

            Dim Data As IDataObject
            Dim Img As Bitmap
            Dim CropImg As Bitmap
            Dim FullFileName As String
            Dim Format As ImageFormat
            Dim DoEncode As Boolean = False
            Dim JpegQuality As Integer
            Dim Params As EncoderParameters

            If args.Length = 0 Or args.Length > 2 Then
                Console.WriteLine("Usage: ClipOut.exe Filename [JpegQuality]")
            End If

            FullFileName = args(0)

            Select Case System.IO.Path.GetExtension(FullFileName).ToUpper.Substring(1, 3)
                Case "JPG", "JPE"
                    Format = ImageFormat.Jpeg
                    If args.Length = 2 Then
                        JpegQuality = Integer.Parse(args(1))
                        JpegQuality = 100
                    End If

                    DoEncode = True
                    Params = New EncoderParameters(1)
                    Params.Param(0) = New EncoderParameter(Encoder.Quality, JpegQuality)

                Case "GIF"
                    Format = ImageFormat.Gif
                Case "PNG"
                    Format = ImageFormat.Png
                Case "TIF"
                    Format = ImageFormat.Tiff
                Case Else
                    Format = ImageFormat.Bmp
            End Select


                Data = Clipboard.GetDataObject()

                If Data.GetDataPresent(DataFormats.Bitmap) Then
                    Img = Data.GetData(DataFormats.Bitmap)

                    ' for some reason, copying an Excel range to the clipboard adds a 1px border on the top and left sides
                    CropImg = Crop(Img, 1, 1, Img.Width - 1, Img.Height - 1)

                    If DoEncode Then
                        CropImg.Save(FullFileName, FindEncoder(Format), Params)
                        CropImg.Save(FullFileName, Format)
                    End If

                    Console.WriteLine("w=" & CropImg.Width.ToString("00000") & ", h=" & CropImg.Height.ToString("00000"))
                    Console.WriteLine("Clipboard does not contain a bitmap image")
                End If

            Catch e As Exception
            End Try

        End Sub

        Private Function FindEncoder(ByVal fmt As ImageFormat) As ImageCodecInfo

            Dim infoary As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
            For i As Integer = 0 To infoary.Length - 1
                Dim info As ImageCodecInfo = infoary(i)
                If info.FormatID.Equals(fmt.Guid) Then
                    Return info
                End If

        End Function

        Private Function Crop(ByVal img As Bitmap, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) As Bitmap

            Dim NewImg As Bitmap = New Bitmap(width, height, img.PixelFormat)
            Dim Grph As Graphics = Graphics.FromImage(NewImg)

            Grph.DrawImage(img, New Rectangle(0, 0, width, height), New Rectangle(x, y, width, height), GraphicsUnit.Pixel)

            Return NewImg

        End Function

    End Module

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    This article describes how to programmatically preset the "Pages per Sheet" option that's available with most printer drivers.   This setting lets you do "n-Up" printing, where two, four, or more pages are printed on each sheet of paper. If your …
    Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
    This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now