python - 使用 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 设备上正常显示。我认为这可能有助于理解原因。从意图返回后,以相同方式读取的相同图像显示为黑色。
解决方案
这可能是线程/gl 上下文问题,您可以尝试将mainthread
装饰器添加到您的on_activity_result
函数中吗?
from kivy.clock import mainthread
...
@mainthread
def on_activity_result(request, response, data):
...
推荐阅读
- c - C:在将具有数组的指针传递给函数时,会出现运行时错误。为什么?
- java - 将 Jetty 从 9.3 更新到 9.4 后,Javamail 出现非常奇怪的问题
- ffmpeg - 如何将具有 DRM 许可证的 mpeg dash (MPD) 转换为 MP4?
- php - Nginx 和 php-fpm 仅适用于某些 php 页面。怎么了?
- javascript - Javascript中的类字段和属性有什么区别
- scala - 为什么 Some(null) 在 Spark 2.4 中抛出 NullPointerException(但在 2.2 中有效)?
- node.js - Angular Universal TTFb 需要很长时间才能响应
- python - 将字典中的一些值相乘
- python - TypeError("'_io.TextIOWrapper' 对象不可调用")
- javascript - Firebase 在登录后注销用户