Android Studio 实例:向SQLite存取BLOB图片数据 探究

先贴出代码,后面进行探究:参考W3cSchool

保存ImageView的图片,但需要指定格式

public void saveImage(ImageView image){
        try {
            ByteArrayOutputStream outs=new ByteArrayOutputStream();
            ((BitmapDrawable)image.getDrawable()).getBitmap().compress(
                    Bitmap.CompressFormat.PNG,100,outs
            );
            Object[] args=new Object[]{outs.toByteArray()};
            db.execSQL("insert into userimage(iamge) values(?)",args);
            outs.close();
            db.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
public void getImage(ImageView imageView){
        Cursor cursor=db.rawQuery("select iamge from userimage",null);
        byte[]img = new byte[0];
        if (cursor!=null){
            if (cursor.moveToFirst()){
                img=cursor.getBlob(cursor.getColumnIndex("iamge"));
            }
        }
        cursor.close();
        if (img!=null){
            ByteArrayInputStream bin=new ByteArrayInputStream(img);
            imageView.setImageDrawable(Drawable.createFromStream(bin,"img"));
        }
    }

猜你喜欢

转载自blog.csdn.net/m0_59558544/article/details/130592648