我正在测试将包含多个图像的zip文件加载到kivy图像的能力,并证明它将循环遍历所有图像。
我之前尝试过这些示例:
https://groups.google.com/forum/#!topic/kivy-users/t_iKvpgLIzE https://kivy.org/docs/api-kivy.core.image.html
我可以让这些工作,但是,我找不到在这种情况下加载 .zip 文件或 .gif 文件的示例。
我请求查看如果 zip 文件位于内存中,是否可以加载包含图像的 zip 文件。或者是否可以从内存加载的图像创建动画。
import io
import zipfile
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class testApp(App):
def get_image_from_memory(self):
with io.BytesIO(open("archer_F_idle.zip", "rb").read()) as f:
imgzip = f.read()
print(imgzip)
zipped_imgs = zipfile.ZipFile(f)
print(zipped_imgs, zipped_imgs.namelist(),zipped_imgs.filename)
return Image(source=zipped_imgs)
def build(self):
self.b = BoxLayout()
self.b.add_widget(self.get_image_from_memory())
return self.b
if __name__ == '__main__':
testApp().run()
这里有以下错误:
ValueError: Image.source accept only str
这是工作示例。确保您将 zip 文件名和图像 exc/文件名更改为您的:
import io
import zipfile
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class testApp(App):
def get_image_from_memory(self):
with zipfile.ZipFile("C:/Users/gmn/Downloads/Cover.zip") as myzip:
with myzip.open('Cover.jpg') as myfile:
ci = CoreImage(io.BytesIO(myfile.read()), ext="jpg")
return Image(texture=ci.texture)
def build(self):
self.b = BoxLayout()
self.b.add_widget(self.get_image_from_memory())
return self.b
if __name__ == '__main__':
testApp().run()
更新:
Zip 文件应包含一张或多张图像。
import io
import zipfile
from itertools import cycle
from kivy.clock import Clock
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
class ZipAnimationImage(Image):
zip_source = StringProperty('')
def __init__(self, **kwargs):
self._cycle = None
super(Image, self).__init__(**kwargs)
Clock.schedule_interval(self._update, 1.0)
def _update(self, *args):
if self._cycle:
self.texture = next(self._cycle).texture
def on_zip_source(self, *args):
cis = []
with zipfile.ZipFile(self.zip_source) as z:
names = z.namelist()
for name in names:
ext = name.split('.')[-1]
with z.open(name) as f:
ci = CoreImage(io.BytesIO(f.read()), ext=ext)
cis.append(ci)
self._cycle = cycle(cis) if cis else None
class testApp(App):
def build(self):
self.b = BoxLayout()
self.b.add_widget(ZipAnimationImage(zip_source='C:/Users/gmn/Downloads/test.zip'))
return self.b
if __name__ == '__main__':
testApp().run()
我是一名优秀的程序员,十分优秀!