使用 Intent 后,用户输入的图像在 kivy 中显示为黑色

Image inputed from user is displayed black in kivy after using Intent

我希望 android 应用程序的用户使用绑定到 activity 的 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'

如果我在没有从 intent 返回的情况下更改图像的纹理,它会在 android 设备上正常显示。我认为这可能有助于了解原因。从一个intent返回后,同样的方式读取的同一张图片显示为黑色。

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

from kivy.clock import mainthread

...

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