How to save pygame Surface as an image to memory (and not to disk)

2024/10/14 14:19:36

I am developing a time-critical app on a Raspberry PI, and I need to send an image over the wire. When my image is captured, I am doing like this:

# pygame.camera.Camera captures images as a Surface
pygame.image.save(mySurface,'temp.jpeg')
_img = open('temp.jpeg','rb')
_out = _img.read()
_img.close()
_socket.sendall(_out)

This is not very efficient. I would like to be able to save the surface as an image in memory and send the bytes directly without having to save it first to disk.

Thanks for any advice.

EDIT: The other side of the wire is a .NET app expecting bytes

Answer

The simple answer is:

surf = pygame.Surface((100,200)) # I'm going to use 100x200 in examples
data = pygame.image.tostring(surf, 'RGBA')

and just send the data. But we want to compress it before we send it. So I tried this

from StringIO import StringIO
data = StringIO()
pygame.image.save(surf, x)
print x.getvalue()

Seems like the data was written, but I have no idea how to tell pygame what format to use when saving to a StringIO. So we use the roundabout way.

from StringIO import StringIO
from PIL import Image
data = pygame.image.tostring(surf, 'RGBA')
img = Image.fromstring('RGBA', (100,200), data)
zdata = StringIO()
img.save(zdata, 'JPEG')
print zdata.getvalue()
https://en.xdnf.cn/q/69403.html

Related Q&A

Plotting Precision-Recall curve when using cross-validation in scikit-learn

Im using cross-validation to evaluate the performance of a classifier with scikit-learn and I want to plot the Precision-Recall curve. I found an example on scikit-learn`s website to plot the PR curve …

The SECRET_KEY setting must not be empty || Available at Settings.py

I tried to find this bug, but dont know how to solve it.I kept getting error message "The SECRET_KEY setting must not be empty." when executing populate_rango.pyI have checked on settings.py …

Pandas: Applying Lambda to Multiple Data Frames

Im trying to figure out how to apply a lambda function to multiple dataframes simultaneously, without first merging the data frames together. I am working with large data sets (>60MM records) and I …

scipy.minimize - TypeError: numpy.float64 object is not callable running

Running the scipy.minimize function "I get TypeError: numpy.float64 object is not callable". Specifically during the execution of:.../scipy/optimize/optimize.py", line 292, in function_w…

Flask, not all arguments converted during string formatting

Try to create a register page for my app. I am using Flask framework and MySQL db from pythonanywhere.com. @app.route(/register/, methods=["GET","POST"]) def register_page(): try:f…

No module named objc

Im trying to use cocoa-python with Xcode but it always calls up the error:Traceback (most recent call last):File "main.py", line 10, in <module>import objc ImportError: No module named …

Incompatible types in assignment (expression has type List[nothing], variable has type (...)

Consider the following self-contained example:from typing import List, UnionT_BENCODED_LIST = Union[List[bytes], List[List[bytes]]] ret: T_BENCODED_LIST = []When I test it with mypy, I get the followin…

How to convert XComArg to string values in Airflow 2.x?

Code: from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.providers.google.cloud.hooks.gcs import GCSHookclass GCSUploadOperator(BaseOperator):@appl…

Python dryscrape scrape page with cookies

I wanna get some data from site, which requires loggin in. I log in by requestsurl = "http://example.com" response = requests.get(url, {"email":"[email protected]", "…

Python retry using the tenacity module

Im having having difficulty getting the tenacity library to work as expected. The retry in the following test doesnt trigger at all. I would expect a retry every 5 seconds and for the log file to refle…