Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martinandersen3d/2de4d79641f71fdd34c8e92963ecd3ff to your computer and use it in GitHub Desktop.
Save martinandersen3d/2de4d79641f71fdd34c8e92963ecd3ff to your computer and use it in GitHub Desktop.
Python Copy gif to clipboard on windows
# The steps are:
# 1. convert a gif to a base64 html image
# 2. copy HTML to clipboard
# 3. in MS Word, paste the html-gif
# Note: This does not work in Gmail, Google Docs and google products
import base64
import win32clipboard
class ClipboardHelper:
DEFAULT_HTML_BODY = '<html><body>%s</body></html>'
def PutFragment(self, fragment, selection=None, html=None, source=None):
if selection is None:
selection = fragment
if html is None:
html = self.DEFAULT_HTML_BODY % fragment
if source is None:
source = "file://HtmlClipboard.py"
fragmentStart = html.index(fragment)
fragmentEnd = fragmentStart + len(fragment)
selectionStart = html.index(selection)
selectionEnd = selectionStart + len(selection)
self.PutToClipboard(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source)
def PutToClipboard(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source="None"):
try:
win32clipboard.OpenClipboard(0)
win32clipboard.EmptyClipboard()
src = self.EncodeClipboardSource(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source)
if src is not None:
src = src.encode("UTF-8")
win32clipboard.SetClipboardData(self.GetCfHtml(), src)
finally:
win32clipboard.CloseClipboard()
def EncodeClipboardSource(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source):
encoded_source = f"Version:1.0\r\nStartHTML:{fragmentStart:09d}\r\nEndHTML:{fragmentEnd:09d}\r\nStartFragment:{selectionStart:09d}\r\nEndFragment:{selectionEnd:09d}\r\nSourceURL:{source}\r\n{html}"
return encoded_source
def GetCfHtml(self):
return win32clipboard.RegisterClipboardFormat("HTML Format")
# Usage example
if __name__ == "__main__":
helper = ClipboardHelper()
# 1. Read GIF file from filepath
gif_filepath = "C:\\Github\\Python\\PythonUniversalSnippetManager\\Samples\\image_2_transparent.gif"
with open(gif_filepath, "rb") as gif_file:
gif_data = gif_file.read()
# 2. Convert GIF into Base64 HTML element
base64_gif = base64.b64encode(gif_data).decode("utf-8")
gif_html = f'<img src="data:image/gif;base64,{base64_gif}">'
# 3. Copy the HTML to memory
helper.PutFragment(gif_html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment