How would it be possible to create an image cropper #4414
-
QuestionHi, I've been attempting to somehow load some existing js tools like cropper.js and init it on top of a ui.image element, but it's just not working. This is a very simple example of what I tried(I tried to import croppie.js as well, and a script using that - but to no avail): ui.add_head_html("""
<script src="https://unpkg.com/cropperjs"></script>
""")
with ui.row(align_items="center").classes("w-full justify-center"):
ui.space()
ui.image("https://picsum.photos/640/360").props("id=crop-image").style("width:382px; height:172px;")
ui.space()
await ui.run_javascript("""
var cropimage = document.getElementById("crop-image")
console.log(cropimage)
const cropper = new Cropper('#image');
""") But this just can't run as it cannot find Copper function, similarly with croppie.js, and I can't use explicit imports. I also tried to import a .js script that would init it but that was basically not registered. How would I be able to implement this with using just nicegui elements? Is that even possible? Or should I just create a request to add something like cropper as a module? As I'm not really skilled enough in JS or Vue or Node to make/integrate a custom module myself into nicegui. Thanks for any help or guidance in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @siren15, I'm not familiar with cropperjs, so it's hard to tell how easily you can integrate it with a NiceGUI app. But using our from PIL import Image
from nicegui import events, ui
IMAGE_PATH = 'website/static/logo.png'
start: dict[str, float] = {}
def handle_mouse(e: events.MouseEventArguments) -> None:
if e.type == 'mousedown':
start.update(x=e.image_x, y=e.image_y)
elif start:
top = min(start['x'], e.image_x)
left = min(start['y'], e.image_y)
width = abs(start['x'] - e.image_x)
height = abs(start['y'] - e.image_y)
img.content = f'<rect x={top} y={left} width={width} height={height} stroke="red" fill="none" />'
if e.type == 'mouseup':
image = Image.open(IMAGE_PATH)
cropped_image = image.crop((top, left, top + width, left + height))
ui.image(cropped_image).classes(f'w-[{width}px]')
img.content = ''
start.clear()
img = ui.interactive_image(IMAGE_PATH, cross=True, on_mouse=handle_mouse, events=['mousedown', 'mousemove', 'mouseup'])
ui.run() |
Beta Was this translation helpful? Give feedback.
Hi @siren15,
I'm not familiar with cropperjs, so it's hard to tell how easily you can integrate it with a NiceGUI app.
But using our
ui.interactive_image
you can build an image crop tool rather quickly: