Search code examples
pythonpython-imaging-librarypngclipboardbmp

How to convert Clipboard Image BMP to PNG using Pillow package without saving and then loading


I would like to convert an image obtained from the Windows Clipboard to PNG format without having to save and then reload.

As per the code below, I am saving the clipboard image and then reloading it.
Is there a way to convert the image to PNG format without those extra steps, such that the

  • PIL.BmpImagePlugin.DibImageFile gets converted to

  • PIL.PngImagePlugin.PngImageFile



Here is the current code:

from PIL import ImageGrab, Image

# Get the clipboard image
img1 = ImageGrab.grabclipboard()

# Save the image from the clipboard to file
img1.save('paste.png', 'PNG')
print("Image Type1:", type(img1))

# Load the image back in
img2 = Image.open('paste.png')
print("Image Type2:", type(img2))

OUTPUT:

Image Type1: <class 'PIL.BmpImagePlugin.DibImageFile'>
Image Type2: <class 'PIL.PngImagePlugin.PngImageFile'>

Solution

  • As per some help from Seon's comment, this got me on the right track, and fulfilled my requirements.

    As per Seon:

    "the idea is to save the image to an in-memory BytesIO object, and reload it from there. We're still saving and loading, but not to disk."

    Which is exactly what I wanted.
    Here is the code I used:

    from PIL import ImageGrab, Image
    import io
    
    
    def convertImageFormat(imgObj, outputFormat="PNG"):
        newImgObj = imgObj
        if outputFormat and (imgObj.format != outputFormat):
            imageBytesIO = io.BytesIO()
            imgObj.save(imageBytesIO, outputFormat)
            newImgObj = Image.open(imageBytesIO)
            
        return newImgObj
    
    
    # Get the clipboard image and convert to PNG
    img1 = ImageGrab.grabclipboard()
    img2 = convertImageFormat(img1)
    
    # Check the types
    print("Image Type1:", type(img1))
    print("Image Type2:", type(img2))
    
    

    OUTPUT:

    Image Type1: <class 'PIL.BmpImagePlugin.DibImageFile'>
    Image Type2: <class 'PIL.PngImagePlugin.PngImageFile'>