如何在Android的Glide中显示数据库图像

如何在Android的Glide中显示数据库图像

本文介绍了如何在Android的Glide中显示数据库图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个 SqliteDatabase .在此数据库中,我保存了 Sting Blob(用于保存图像).此图像使用 byte [] 保存在应用程序中.我借助以下代码将该图像转换为Bitmap:

I have a SqliteDatabase in my application. In this database, I save Sting and Blob(for save image). This image is saved in application with byte[ ]. I convert this image to Bitmap with the help of following code:

    byte[] Recycler_imageByte;
    Bitmap Recycler_theImage;

holder.Recycler_imageByte = data.get(position).getKey_image();
ByteArrayInputStream imageStream = new ByteArrayInputStream(holder.Recycler_imageByte);
holder.Recycler_theImage = BitmapFactory.decodeStream(imageStream);

我想在 Glide 库中显示此图像,我编写了以下代码:

I want to show this image in Glide libary, I have written the following code:

Glide.with(context).load(holder.Recycler_theImage).asBitmap().into(holder.Recycler_adapter_image);

但是,当我运行应用程序时,显示以下错误:

But, when I run application, following error is shown:

03-15 10:23:14.311 22440-22440/com.tellfa.dastanak E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tellfa.dastanak, PID: 22440
java.lang.IllegalArgumentException: Unknown type class android.graphics.Bitmap. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tellfa.dastanak.Adapters.fragment_RecyclerAdapter.onBindViewHolder(fragment_RecyclerAdapter.java:54)
at com.tellfa.dastanak.Adapters.fragment_RecyclerAdapter.onBindViewHolder(fragment_RecyclerAdapter.java:27)
at jp.wasabeef.recyclerview.adapters.AnimationAdapter.onBindViewHolder(AnimationAdapter.java:55)
at jp.wasabeef.recyclerview.adapters.AnimationAdapter.onBindViewHolder(AnimationAdapter.java:55)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5217)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5250)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4487)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1370)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2900)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3071)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:584)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1627)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1037)
at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:747)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1156)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:760)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1043)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(Vi

如何修复它并在Glide库中显示位图?谢谢大家.

How can I fix it and show bitmap in Glide library? Thanks all.

推荐答案

使用以下方法将图像转换为字节数组并以BLOB形式存储到数据库中

Use following method for convert image to byte array and store into database as BLOB

public String bitmapToString(Bitmap bmp) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
        byte[] bytes = os.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

并且当您想使用Glide进入图像视图时,请使用以下

And when you want to show into image view using Glide use following

public void stringToBitmap(String str) {
        byte[] bytesImage = Base64.decode(str, Base64.DEFAULT);
        //Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0, bytesImage.length);
        //ivImage.setImageBitmap(bitmap);
        // using glide
        Glide.with(this).load(bytesImage).asBitmap().into(ivImage);
    }

从数据库存储和检索图像的简单示例

Simple example of storing and retrieving image from database

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnInsert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Insert into DB" />

    <Button
        android:id="@+id/btnView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="View from DB" />

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private DatabaseHelper databaseHelper;
    private SQLiteDatabase db;
    private Button btnInsert, btnView;
    private ImageView ivImage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper = new DatabaseHelper(this);
        db = databaseHelper.getWritableDatabase();

        ivImage = (ImageView) findViewById(R.id.ivImage);
        btnInsert = (Button) findViewById(R.id.btnInsert);
        btnView = (Button) findViewById(R.id.btnView);


        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertImage();
            }
        });

        btnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewFromDb();
            }
        });

    }

    private void insertImage() {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ContentValues values = new ContentValues();
        values.put("image", bitmapToString(bmp));
        db.insert("table_image", null, values);
        Toast.makeText(this, "Insert Successful",Toast.LENGTH_SHORT).show();
    }

    private void viewFromDb() {
        String sql = "select * from table_image";
        ArrayList<String> images = new ArrayList<>();
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                String img = cursor.getString(cursor.getColumnIndex("image"));
                images.add(img);
                cursor.moveToNext();
            }
        }
        cursor.close();
        if (images.size() > 0) {
            // get last image
            stringToBitmap(images.get(images.size()-1));
        }
    }


    public String bitmapToString(Bitmap bmp) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
        byte[] bytes = os.toByteArray();
        //return Base64.encodeToString(bytes, Base64.DEFAULT);
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public void stringToBitmap(String str) {
        byte[] bytesImage = Base64.decode(str, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0, bytesImage.length);
        ivImage.setImageBitmap(bitmap);
        //Glide.with(this).load(bytesImage).asBitmap().into(ivImage);
    }
}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";

    public static String DB_PATH;
    public static String DB_NAME = "mdb";

    private static SQLiteDatabase myDataBase;
    private static DatabaseHelper helperInstance;
    private final Context myContext;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
        DB_PATH = "/data/data/" + myContext.getPackageName() + "/databases/";
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e(TAG, "On Create");
        String sql = "CREATE TABLE IF NOT EXISTS table_image (_id INTEGER PRIMARY KEY AUTOINCREMENT, image BLOB)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

我希望它对您有用.

这篇关于如何在Android的Glide中显示数据库图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 09:34