如何在android中从mssql数据库varbinary(max)检索图像到位图?

46qrfjad  于 2021-07-29  发布在  Java
关注(0)|答案(0)|浏览(226)

我想从ms sql数据库检索一个图像。在数据库中,它存储为varbinary(max)类型,但在android中,我需要将它转换为位图。
但当我运行代码时,它总是抛出 IllegalArgumentException: bad base-64 在数据库的列中,其存储方式如下: 0x5B42403965393862316230 但在应用程序中,它总是这样返回 [B@9ea047a8 .
以下是保存图像的代码(运行正常):

public User saveProfilPicture(User user){
        Connection con = DBConnection.connection();
        try {

            Bitmap captureImage = user.getProfilImage();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            captureImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            byte[] bytes = byteArrayOutputStream.toByteArray();

            PreparedStatement update = con.prepareStatement("UPDATE dbo.[User] 
SET profilImage = (CONVERT(VARBINARY(MAX), '"+ bytes +"')) WHERE userID = " + user.getUserID()+";");
            update.executeUpdate();
            user.setCreateStatus(true);

        } catch (SQLException e2) {
            e2.printStackTrace();
            user.setCreateStatus(false);
        }

        return user;
    }

以下是检索图像的代码(存在错误):

public User findProfilPicture(User user)  {
        Connection con = DBConnection.connection();
        try{
            PreparedStatement get = con.prepareStatement("SELECT  CONVERT(VARBINARY(MAX), 
[profilImage]) AS profilImage FROM dbo.[User] WHERE userID =" + user.getUserID() +";");
            System.out.println(get.toString());
            ResultSet rs = get.executeQuery();
            if (rs.next()) {

                byte[] bytesResult = rs.getBytes("profilImage");
                byte[] bytes = Base64.decode(String.valueOf(bytesResult), Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0, bytes.length);

                user.setProfilImage(bitmap);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return user;
    }

哪里出错了?你能解释一下吗?谢谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题