首页 > 解决方案 > 如何从 MS SQL 数据库 varbinary(max) 检索图像到 Android 中的位图?

问题描述

我想从 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;
    }

错误在哪里?你可以解释吗?谢谢。

标签: androidsqlsql-serverbitmapbase64

解决方案


推荐阅读