File size: 1,452 Bytes
585ffc7
 
73ecc02
 
 
 
585ffc7
 
73ecc02
585ffc7
 
 
 
e258875
585ffc7
 
73ecc02
 
 
 
 
e72d206
73ecc02
 
 
585ffc7
 
9a148d1
73ecc02
 
 
 
 
9a148d1
73ecc02
 
 
 
9a148d1
73ecc02
 
 
 
585ffc7
73ecc02
 
 
 
 
 
 
585ffc7
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import base64
from io import BytesIO
import cv2
from PIL import Image
import numpy as np
import gradio as gr


def encode(image):
    if image is None:
        raise gr.Error('No input image')

    buffer = BytesIO() 
    image.save(buffer, format='PNG')
    img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
    return img_str

def decode(image_str):
    if image_str is None:
        raise gr.Error('No input image string')

    image_byte = base64.b64decode(image_str)
    image = cv2.imdecode(np.frombuffer(image_byte, np.uint8), cv2.IMREAD_UNCHANGED)
    image = Image.fromarray(image[:,:,::-1])
    return image
    
with gr.Blocks() as demo:
    with gr.Tab(label='Encoding'):
        with gr.Row():
            with gr.Column():
                image = gr.Image(type='pil', interactive=True)
                btn_enc = gr.Button()
            output_image_str = gr.Textbox(label='image string', interactive=False)
    with gr.Tab('Decoding'):
        with gr.Row():
            with gr.Column():
                image_str = gr.Textbox(label='image string', interactive=True)
                btn_dec = gr.Button()
            output_image = gr.Image(type='pil', interactive=False)
            

    btn_enc.click(
        fn=encode,
        inputs=[image],
        outputs=[output_image_str],
    )

    btn_dec.click(
        fn=decode,
        inputs=[image_str],
        outputs=[output_image],
    )

demo.launch(show_error=True)