Skip to content

Instantly share code, notes, and snippets.

@a-nakanosora
Last active June 6, 2022 14:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a-nakanosora/9493b14836fe054294ade772e1df8c68 to your computer and use it in GitHub Desktop.
Save a-nakanosora/9493b14836fe054294ade772e1df8c68 to your computer and use it in GitHub Desktop.
Blender Script draft - Copy image to clipboard
'''
Blender Script - Copy "Viewer Node" image to clipboard
- Windows only
- needs: Python module: Pillow (PIL)
ref:
python - Copy PIL/PILLOW Image to Windows Clipboard - Stack Overflow
http://stackoverflow.com/questions/21319486/copy-pil-pillow-image-to-windows-clipboard
'''
import bpy
import numpy as np
from PIL import Image
def main():
img0 = bpy.data.images['Viewer Node']
W,H = img0.size
#px0 = img0.pixels[:]
px0 = [min(max(v, 0), 1) for v in img0.pixels] ## <!> clamp
pixels = np.array([int(v*255) for v in px0])
pixels.resize(W, H*4)
pixels = np.flipud(pixels).flatten()
import array
pimg = Image.frombytes("RGBA", (W,H), array.array("B", pixels).tostring() ) ## convert pixels(list) to bytes-stream
clipboard_copy_image(pimg)
print('copied the image to clipboard')
def clipboard_copy_image(pimg):
import io
import ctypes
msvcrt = ctypes.cdll.msvcrt
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
output = io.BytesIO()
pimg.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()
CF_DIB = 8
GMEM_MOVEABLE = 0x0002
global_mem = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
global_data = kernel32.GlobalLock(global_mem)
msvcrt.memcpy(ctypes.c_char_p(global_data), data, len(data))
kernel32.GlobalUnlock(global_mem)
user32.OpenClipboard(None)
user32.EmptyClipboard()
user32.SetClipboardData(CF_DIB, global_mem)
user32.CloseClipboard()
main()
@a-nakanosora
Copy link
Author

a-nakanosora commented Nov 4, 2016

To install Pillow into Blender Python:

  1. download get-pip.py from https://pip.pypa.io/en/latest/installing/
  2. install pip & install pillow through pip:
    $ cd blender/2.xx/python
    $ bin/python.exe get-pip.py
    $ Scripts/pip.exe
    $ Scripts/pip install pillow

@a-nakanosora
Copy link
Author

If copied image's colors had changed, check Blender > Scene > "Color Management" settings.

@Ulf3000
Copy link

Ulf3000 commented Aug 29, 2020

it only copies an empty square into memory(black in BMP and just alpha in PNG) , and not even in the size of the render.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment