How to load image through byte array using Glide?

こ雲淡風輕ζ 提交于 2019-12-18 02:02:51

问题


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.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.

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

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.

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.


回答1:


Lets say your base64 string is

String imageBytes = "HVao14fpmtHSev3OgsrQNsawkFzXNcY3BsfQla6..."

You should convert imageBytes String to array of bytes through

byte[] imageByteArray = Base64.decode(imageBytes, Base64.DEFAULT);

afterwards pass this imageByteArray to Glide.

Glide.with(context)
    .load(imageByteArray)
    .asBitmap()
    .placeholder(R.drawable.ic_broken)
    .into(rowImageView);



回答2:


You can convert Base64 String to image using the following

Glide.with(context)
    .load(Base64.decode(base64ImageString, Base64.DEFAULT))
    .asBitmap()
    .placeholder(R.drawable.ic_broken)
    .into(rowImageView);



回答3:


If you are getting error on .asBitmap() just use it like this

             Glide.with(this)
                .asBitmap()
                .load(imageAsBytes)
                .into(image)



回答4:


Kotlin way:

val imageByteArray = Base64.decode(sampleBase64ImageString, Base64.DEFAULT)
Glide.with(this).load(imageByteArray).into(imageView)


来源:https://stackoverflow.com/questions/34588905/how-to-load-image-through-byte-array-using-glide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!