Skip to content

Commit 8f2ad34

Browse files
authored
Merge pull request #284 from martinRenou/fix_draw_image
Fix drawing rgba image
2 parents f5acda4 + b037c1e commit 8f2ad34

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

ipycanvas/utils.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@ def image_bytes_to_array(im_bytes):
2626

2727
def binary_image(ar, quality=75):
2828
f = BytesIO()
29-
PILImage.fromarray(ar.astype(np.uint8), "RGB" if ar.shape[2] == 3 else "RGBA").save(
30-
f, "JPEG", quality=quality
31-
)
29+
if ar.shape[2] == 3:
30+
filetype = "JPEG"
31+
else:
32+
filetype = "PNG"
33+
PILImage.fromarray(ar.astype(np.uint8)).save(f, filetype, quality=quality)
3234
return f.getvalue()
3335

3436

106 KB
Loading

ui-tests/tests/notebooks/ipycanvas.ipynb

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -946,6 +946,35 @@
946946
"\n",
947947
"canvas"
948948
]
949+
},
950+
{
951+
"cell_type": "code",
952+
"execution_count": null,
953+
"id": "2d77c902",
954+
"metadata": {},
955+
"outputs": [],
956+
"source": [
957+
"import numpy as np\n",
958+
"\n",
959+
"from ipycanvas import Canvas\n",
960+
"\n",
961+
"x = np.linspace(-1, 1, 600)\n",
962+
"y = np.linspace(-1, 1, 600)\n",
963+
"\n",
964+
"x_grid, y_grid = np.meshgrid(x, y)\n",
965+
"\n",
966+
"blue_channel = np.array(np.sin(x_grid**2 + y_grid) * 255, dtype=np.int32)\n",
967+
"red_channel = np.zeros_like(blue_channel) + 200\n",
968+
"green_channel = np.zeros_like(blue_channel) + 50\n",
969+
"alpha_channel = blue_channel\n",
970+
"\n",
971+
"image_data = np.stack((red_channel, blue_channel, green_channel, alpha_channel), axis=2)\n",
972+
"\n",
973+
"canvas = Canvas(width=image_data.shape[0], height=image_data.shape[1])\n",
974+
"canvas.put_image_data(image_data, 0, 0)\n",
975+
"\n",
976+
"canvas"
977+
]
949978
}
950979
],
951980
"metadata": {
@@ -964,7 +993,7 @@
964993
"name": "python",
965994
"nbconvert_exporter": "python",
966995
"pygments_lexer": "ipython3",
967-
"version": "3.10.4"
996+
"version": "3.10.5"
968997
},
969998
"widgets": {
970999
"application/vnd.jupyter.widget-state+json": {

0 commit comments

Comments
 (0)