Java 如何使用 Glide 通过字节数组加载图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34588905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load image through byte array using Glide?
提问by Adnan Amjad
I have an image contents byte[] form. But when i load them through Glide then broken images are shown. what I'm doing is shown below.
我有一个图像内容字节 [] 形式。但是当我通过 Glide 加载它们时,会显示损坏的图像。我正在做的如下所示。
Glide.with(context)
.load(imageByteArray)
.asBitmap()
.placeholder(R.drawable.ic_broken)
.into(rowImageView);
imageByteArray successfully converts to bitmap without using glide. So there is no wrong with image byte array.
imageByteArray 在不使用滑行的情况下成功转换为位图。所以图像字节数组没有错。
Please guide me what I'm missing?
请指导我我缺少什么?
Also I'm using Glide library com.github.bumptech.glide:glide:3.6.1 And Android support library com.android.support:support-v13:23.0.1
另外我正在使用 Glide 库 com.github.bumptech.glide:glide:3.6.1 和 Android 支持库 com.android.support:support-v13:23.0.1
Edited
已编辑
Ok, This is what I'm doing.
好的,这就是我正在做的。
String imageBytes = "HVao14fpmtHSev3OgsrQNsawkFzXNcY3BsfQla6..."
This string above defined is bytes of actual image which I'm receiving from web API.
上面定义的这个字符串是我从 Web API 接收到的实际图像的字节。
I'm converting this String into byte array like this
我正在将这个字符串转换成这样的字节数组
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Than I'm applying resultant byte array "imageByteArray" to Glide code defined above.
比我将结果字节数组“imageByteArray”应用于上面定义的 Glide 代码。
采纳答案by Adnan Amjad
Lets say your base64 string is
假设您的 base64 字符串是
String imageBytes = "HVao14fpmtHSev3OgsrQNsawkFzXNcY3BsfQla6..."
You should convert imageBytes
String to array of bytes through
您应该通过将imageBytes
字符串转换为字节数组
byte[] imageByteArray = Base64.decode(imageBytes, Base64.DEFAULT);
afterwards pass this imageByteArray
to Glide.
然后将其传递imageByteArray
给 Glide。
Glide.with(context)
.load(imageByteArray)
.asBitmap()
.placeholder(R.drawable.ic_broken)
.into(rowImageView);
回答by Anudeep Samaiya
You can convert Base64
String to image using the following
您可以Base64
使用以下方法将字符串转换为图像
Glide.with(context)
.load(Base64.decode(base64ImageString, Base64.DEFAULT))
.asBitmap()
.placeholder(R.drawable.ic_broken)
.into(rowImageView);
回答by Zohab Ali
If you are getting error on .asBitmap()
just use it like this
如果您遇到错误,请.asBitmap()
像这样使用它
Glide.with(this)
.asBitmap()
.load(imageAsBytes)
.into(image)
回答by B. León
Kotlin way:
科特林方式:
val imageByteArray = Base64.decode(sampleBase64ImageString, Base64.DEFAULT)
Glide.with(this).load(imageByteArray).into(imageView)