为何我的byte array尺寸小于640×640图片的理论大小?
问题:Spotify专辑封面转byte array长度不符的原因及解决方法
你尝试将640×640的Spotify专辑封面转换为byte array用于32×32 RGB矩阵显示,但代码生成的byte array长度为175742,和理论值640×640×3=1228800不符,原因及解决方法如下:
你的代码
import urllib.request url = "https://i.scdn.co/image/ab67616d0000b2734c63ce517dd44d0fbd9416da" path = "test.jpg" def image_byte(url, file_path): urllib.request.urlretrieve(url, file_path) with open(path, "rb") as image: f = image.read() b = bytearray(f) return b b = image_byte(url, path) print(len(b))
原因分析
你读取的是JPG格式的压缩文件字节,而非原始RGB像素数据:
- JPG是有损压缩图像格式,会通过算法大幅缩小文件体积,所以直接读取JPG文件得到的bytearray是压缩后的文件内容,长度远小于未压缩的原始RGB像素数据量。
- 640×640×3=1228800是未压缩RGB图像的总字节数(每个像素用3个字节存储R、G、B通道数据),这和压缩后的JPG文件大小没有直接关系。
解决方法
要获取原始RGB像素的bytearray,需要用图像处理库(如Pillow)解码图像,再提取像素数据。如果最终要适配32×32 RGB矩阵,还需要先将图像缩小到目标尺寸。
步骤1:安装Pillow库
pip install pillow
步骤2:获取原始640×640 RGB像素的bytearray
import urllib.request from PIL import Image import io url = "https://i.scdn.co/image/ab67616d0000b2734c63ce517dd44d0fbd9416da" def get_image_rgb_bytes(url): # 直接从URL读取图像数据,无需保存本地文件 with urllib.request.urlopen(url) as response: image_data = response.read() # 解码JPG为图像对象 img = Image.open(io.BytesIO(image_data)) # 转换为RGB格式(兼容带Alpha通道的图像) img_rgb = img.convert("RGB") # 提取原始RGB像素的bytearray rgb_bytes = bytearray(img_rgb.tobytes()) return rgb_bytes b = get_image_rgb_bytes(url) print(len(b)) # 输出1228800,与理论值一致
步骤3:获取适配32×32矩阵的RGB像素bytearray
import urllib.request from PIL import Image import io url = "https://i.scdn.co/image/ab67616d0000b2734c63ce517dd44d0fbd9416da" target_size = (32, 32) def get_resized_rgb_bytes(url, target_size): with urllib.request.urlopen(url) as response: image_data = response.read() # 解码并转换为RGB格式 img = Image.open(io.BytesIO(image_data)).convert("RGB") # 缩小图像到目标尺寸,使用LANCZOS算法保证缩画质素 resized_img = img.resize(target_size, Image.Resampling.LANCZOS) # 提取缩小后的RGB像素bytearray rgb_bytes = bytearray(resized_img.tobytes()) return rgb_bytes b = get_resized_rgb_bytes(url, target_size) print(len(b)) # 输出3072,符合32×32 RGB矩阵的需求
内容的提问来源于stack exchange,提问作者tyanne
相关产品推荐
相关产品推荐

