【问题标题】:How to Load Image form mysql database and display in imageview in android?如何从mysql数据库加载图像并在android的imageview中显示?
【发布时间】:2021-09-29 10:15:16
【问题描述】:

我想在数据库中上传用户个人资料图片,然后在片段中显示所有用户的列表。为了将图像资源设置为 imageview,我使用 Glide,当上传到数据库时,我在 base64 中对图像进行编码,我可以从数据库中获取图像路径,但是当设置为 imageview 时不显示任何内容。并且没有显示错误。从数据库检索后是否需要解码?

  private void ChooseFile(){
    Intent intent=new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select picture"),1);

}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==1 && resultCode== RESULT_OK && data!=null && data.getData()!=null){
        Uri filepath=data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),filepath);
            profile_image.setImageBitmap(bitmap);

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

        UploadPicture(getID,getStringimage(bitmap));

    }
}



private void UploadPicture(final String id, final String photo){
   final ProgressDialog progressDialog = new ProgressDialog(getContext());
   progressDialog.setTitle("Uploading your Image");
   progressDialog.setCancelable(false);
   progressDialog.setCanceledOnTouchOutside(false);
   progressDialog.setIndeterminate(false);
   progressDialog.show();
   String uRlP = "http://192.168.8.193:80/worker/Userupload.php";

   StringRequest request = new StringRequest(Request.Method.POST, uRlP, new Response.Listener<String>() {
       @Override
       public void onResponse(String response) {
           Log.d("Login", "Connected");
           try {
               JSONObject jsonObject=new JSONObject(response);
               progressDialog.dismiss();
                   if(!jsonObject.getBoolean("error")){
                       String getp=jsonObject.getString("photo");
                       Log.d("Omag", getp);
                       usersession.setImage(getp);

                       Toast.makeText(getContext(),"Upload Successfully",Toast.LENGTH_LONG).show();

                       Log.d("UploadImg", "Sucess");
                   }else{
                       Toast.makeText(getContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
                       progressDialog.dismiss();
                   }
           } catch (JSONException e) {
               e.printStackTrace();
               progressDialog.dismiss();
               Toast.makeText(getContext(),"Try Again!",Toast.LENGTH_LONG).show();

           }

       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
           Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
           progressDialog.dismiss();
       }
   }){
       @Override
       protected Map<String, String> getParams() throws AuthFailureError {
           HashMap<String,String> param = new HashMap<>();
           param.put("id",id);
           param.put("photo",photo);
            return param;
       }
   };

   request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
   MySingleton.getmInstance(getContext()).addToRequestQueue(request);

}

public String getStringimage(Bitmap bitmap){
    ByteArrayOutputStream byteArrayOutputStream= new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
    byte[] imageByteArray=byteArrayOutputStream.toByteArray();
    String econdeImage= Base64.encodeToString(imageByteArray,Base64.DEFAULT);
    return econdeImage;
}

这段代码从数据库中取回并在 imageview 中设置。

private void getAllData() {
    final ProgressDialog progressDialog = new ProgressDialog(getContext());
    progressDialog.setTitle("Reading your details");
    progressDialog.setCancelable(false);
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setIndeterminate(false);
    progressDialog.setMax(100);
    //progressDialog.show();

    String uRl = "http://192.168.8.193:80/worker/getWorkers.php";

    StringRequest request = new StringRequest(Request.Method.GET, uRl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //  progressDialog.dismiss();
            Log.d("HomeLogin", "Connected");
            if(!response.equals("error")) {
                try {

                    JSONArray array = new JSONArray(response);

                    Log.d("Home", array.getString(1));
                    for (int i = 0; i < array.length(); i++) {
                        Log.d("responess", i+" ");
                        JSONObject object = array.getJSONObject(i);

                        int id = object.getInt("id");
                        String name = object.getString("name");
                        String email = object.getString("email");
                        String gender = object.getString("gender");
                        String mobile = object.getString("mobile");
                        String image = object.getString("photo");
                        Log.d("photo", image);

                        // String rate = String.valueOf(rating);
                        //float newRate = Float.valueOf(rate);

                        float rate = 1.2f;


                        UserData user_data = new UserData(id, name, email, mobile, gender, image, rate);
                        User_Data.add(user_data);
                    }

                } catch (Exception e) {
                    Toast.makeText(getContext(),response+""+e,Toast.LENGTH_LONG).show();
                    Log.d("ErrorH", response+""+e);
                }

                mAdapter = new RecyclerAdapter(getContext(), User_Data);
                recyclerView.setAdapter(mAdapter);
            }else {
                Toast.makeText(getContext(),response,Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            progressDialog.dismiss();

            Toast.makeText(getContext(), error.toString(),Toast.LENGTH_LONG).show();

        }
    });

    request.setRetryPolicy(newDefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MySingleton.getmInstance(getContext()).addToRequestQueue(request);


}

我的 Recycler 视图适配器类,(在 imageview 中设置)

@Override
public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, int position) {

     UserData userInfo = userData.get(position);

    holder.mPrice.setText("Phone: "+userInfo.getMobile());
    holder.mRate.setRating(userInfo.getRating());
    holder.mTitle.setText(userInfo.getName());


    Glide.with(mContext).load(userInfo.getImage()).into(holder.mImageView);

    holder.mContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(mContext,DetailActivity.class);

            intent.putExtra("name",userInfo.getName());
            intent.putExtra("image",userInfo.getImage());
            intent.putExtra("rate",userInfo.getRating());
            intent.putExtra("phone",userInfo.getMobile());

            mContext.startActivity(intent);

        }
    });

}
but nothing displayed. is it need to decode again the image? when retrieved from the database?

【问题讨论】:

  • 当你在 "getAllData()" 中调用 api 时,你在 "object.getString("photo")" 中得到了什么?图片网址还有什么?
  • 我得到这个图片链接:192.168.155.193/worker/profile_image/7.jpeg
  • 您可以使用 glide 直接加载此图像 url。如果这没有加载,那么首先检查适配器是否获取图像 URL。如果您在适配器中获取图像 url,则在浏览器中打开 URL。如果这些都不起作用,则解码保存的图像并将其转换为 bimap 然后设置。
  • 你有转换的示例代码吗?当我浏览图片 URL 时,我得到了图片。
  • 嘿,我发现了问题。它显示了这个。:W/Glide: Load failed for 192.168.155.193/worker/profile_image/13.jpeg with size [510x450] class com.bumptech.glide.load.engine.GlideException: 加载资源失败有 1 个根本原因:这意味着问题出在图像的大小。这个怎么解决??

标签: android mysql image android-recyclerview android-volley


【解决方案1】:

您可以将文件路径而不是文件存储在数据库中, 您可以使用此方法在新的 android 和旧版本中从 uri 获取文件

fun getFileFromUri(uri: Uri): File? {
if (uri.path == null) {
    return null
}
var realPath = String()
val databaseUri: Uri
val selection: String?
val selectionArgs: Array<String>?
if (uri.path!!.contains("/document/image:")) {
    databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    selection = "_id=?"
    selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
} else {
    databaseUri = uri
    selection = null
    selectionArgs = null
}
try {
    val column = "_data"
    val projection = arrayOf(column)
    val cursor = context.contentResolver.query(
        databaseUri,
        projection,
        selection,
        selectionArgs,
        null
    )
    cursor?.let {
        if (it.moveToFirst()) {
            val columnIndex = cursor.getColumnIndexOrThrow(column)
            realPath = cursor.getString(columnIndex)
        }
        cursor.close()
    }
} catch (e: Exception) {
    Log.i("GetFileUri Exception:", e.message ?: "")
}
val path = if (realPath.isNotEmpty()) realPath else {
    when {
        uri.path!!.contains("/document/raw:") -> uri.path!!.replace(
            "/document/raw:",
            ""
        )
        uri.path!!.contains("/document/primary:") -> uri.path!!.replace(
            "/document/primary:",
            "/storage/emulated/0/"
        )
        else -> return null
    }
}
return File(path)}

【讨论】:

  • 你的意思是把图片本身存入数据库列吗??不在 profile_image 文件夹中?
  • 我的意思是只是将文件 uri 存储在数据库中,而不是将整个文件存储在某个地方或数据库或其他东西中,只需使用图像 uri
  • 好的,我会试试的。路径有问题??
  • 我只是给你建议了另一种解决方案,因为我觉得你不必将文件保存在数据库中,更好的方法是将图像 uri 存储在数据库中
  • 是的,我需要图片网址。这段代码有什么问题?任何想法?我可以获取图像 URL 表单数据库:172.16.204.105/worker/profile_image/7.jpeg。当我传递给 recyclerview 适配器并设置为 imageview 时没有显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多