首页 > 解决方案 > 使用 Intent 后,从用户输入的图像在 kivy 中显示为黑色

问题描述

我希望 android 应用程序的用户使用绑定到活动的 on_activity_result 函数输入图像,然后将其显示在 kivy 图像小部件中。我使用 Intent.createChooser 作为用户输入:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.app import App
from kivy.uix.image import Image, CoreImage

class MainApp(App):
    def build(self):
        return Builder.load_file('main.kv')
    def set_texture(self, root):
        i = root.children[0].children[0] # getting the image widget
        ##set the image as bytes
        with open("./small image.png", "rb") as image:
            f = image.read()
            bytesArray = bytearray(f)
        import io
        img = CoreImage(io.BytesIO(bytesArray), ext="png").texture      
        i.texture = img
    def set_texture_after_intent(self):
        from jnius import autoclass, cast
        from android import activity
        activity.bind(on_activity_result=on_activity_result)
        PythonActivity = autoclass("org.kivy.android.PythonActivity")
        context = PythonActivity.mActivity
        currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
        AndroidString = autoclass('java.lang.String')
        Intent = autoclass('android.content.Intent')
        intent = Intent()
        intent.setType("image/*")
        intent.setAction(Intent.ACTION_GET_CONTENT)
        currentActivity.startActivityForResult(
        Intent.createChooser(intent, cast('java.lang.CharSequence', AndroidString("Select Picture"))), 1)

def on_activity_result(request, response, data):
    #get the image widget
    root = App.get_running_app().root
    #call same display function
    App.get_running_app().set_texture(root)

MainApp().run()

.kv 文件:

Screen:
    id:myscreen
    BoxLayout:
        Button:
            text:'change image normally'
            on_release: app.set_texture(root)
        Button:
            text:'change image after intent'
            on_release: app.set_texture_after_intent()
        Image:
            id: image_id
            source:'./big image.png'

如果我更改图像的纹理而不从意图中恢复,它会在 Android 设备上正常显示。我认为这可能有助于理解原因。从意图返回后,以相同方式读取的相同图像显示为黑色。

标签: pythonpython-3.xkivykivymd

解决方案


这可能是线程/gl 上下文问题,您可以尝试将mainthread装饰器添加到您的on_activity_result函数中吗?

from kivy.clock import mainthread

...

@mainthread
def on_activity_result(request, response, data):
    ...

推荐阅读