1

I try to do:

  • take screenshot using python-mss
  • resize and then convert to base64
  • using JS load by ajax using python-flask request handler and paste the result to src attribute in img tag like data:image/png;base64,{{base64}}

HTML result:

get_base64_screenshot.py

import mss, cv2, base64
import numpy as np

MSS = mss.mss()

# screenshot
frame_bytes = MSS.grab(MSS.monitors[2])

# BGRA -> RGB
frame_array = np.array(frame_bytes)
frame_array = np.flip(frame_array[:, :, :3], 2)

# resize
frame_resized = cv2.resize(frame_array, (640, 360), interpolation = cv2.INTER_CUBIC)

# base64
frame_base64 = base64.b64encode(frame_resized)

What am I doing wrong? I think it's wrong decoding.

0

1 Answer 1

3

You are encoding the raw cv2 image data as base64, which your web browser won't understand. You need to encode the raw image data to jpg and then encode it.

# resize
frame_resized = cv2.resize(frame_array, (640, 360), interpolation = cv2.INTER_CUBIC)

encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
result, frame_encoded = cv2.imencode('.jpg', frame_resized, encode_param)

# base64
frame_base64 = base64.b64encode(frame_encoded)

code snippet taken from here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.