问题描述
注意:我在这里找到的关于堆栈溢出的大多数答案要么已经过时(并且使用了已弃用的方法),要么密切相关但对我的情况并不完全有用
我正在制作一个应用程序,可根据用户输入的图像生成调色板。我正在使用 this Jetpack library 为了达成这个。我非常菜鸟,以前从未处理过位图或此类意图。我相信启动图像选择器的代码应该如下所示:
const val PICK_IMAGE = 1
class MainActivity : AppCompatActivity() {
private lateinit var opengalleryButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
opengalleryButton = findViewById(R.id.open_gallery_button)
opengalleryButton.setonClickListener {
val photoPickerIntent = Intent(Intent.ACTION_PICK)
photoPickerIntent.type = "image/*"
startActivityForResult(photoPickerIntent,PICK_IMAGE)
}
}
}
那么我想我必须覆盖 onActivityResult()
并在那里做点什么?但无论我做什么,我都无法让它发挥作用。我不希望将此图像设置为任何 ImageView
,并且对类似问题的大多数答案仅回答如何将图像设置为 ImageView
或已过时并使用已弃用的方法。
我想在用户按下按钮时从用户那里获取图像,以某种方式将其转换为可以在调色板库中使用的位图。从生成的调色板中获取主色作为十六进制颜色或其他一些可用格式并自己处理。
解决方法
https://github.com/SvenWoltmann/color-thief-java
以下是一些可能对您的项目有用的逻辑。 简单的代码片段:
var colorThief = new ColorThief();
var sourceImage = document.getElementById("image");
// Display main color
// e.g [125,189,193]
console.log(
colorThief.getColor(sourceImage)
);
// Display palette of colors
// e.g [[55,37,29],[213,193,136],[110,204,223]]
console.log(
colorThief.getPalette(sourceImage)
);
或者您可以使用 Vibrant,这是一个流行的 Java 库的 JavaScript 端口:
http://jariz.github.io/vibrant.js/
,所以@blackapps 回答了这个问题,这个问题的解决方案是通过传入图像 URI 来启动带有内容解析器的输入流。获得 URI 后,使用位图工厂对流进行解码,然后将返回您的位图。
val inputStream = contentResolver.openInputStream(selectedImageUri)
val bitmap = BitmapFactory.decodeStream(inputStream)