简体   繁体   English

将图像存储在数据库中并检索以回显为json

[英]storing images in database and retrieving it to echo as json

I know this question have been asked many times but I am really having a problem understanding what is happening 我知道这个问题已经问过很多次了,但是我真的很难理解正在发生的事情

I have a project to make an android app that uses the same database as a website my partner is working on 我有一个项目要制作一个与我的伴侣正在使用的网站使用相同数据库的android应用

and my problem is working with images 我的问题是处理图像

I know that we should not store images in the database....but we have too here 我知道我们不应该将图像存储在数据库中....但是我们在这里也有

the images are getting stored in the data base as blob and it's working fine on the website but not on my app 图像以blob的形式存储在数据库中,并且在网站上工作正常,但在我的应用程序上却无法正常工作

I loaded to the app some of the images uploaded to database from the website and some that I have uploaded using the interface of sql wamp server 我将一些从网站上传到数据库的图像加载到应用程序中,并且使用sql wamp服务器的界面上传了一些图像

and they work fine 他们工作正常

but when I upload an image from my app to the database when I fetch it back it doesn't show up at all 但是当我将图像从应用程序上传回数据库时,它根本没有显示

here is what I'm doing 这是我在做什么

I start an intent to pick an image with this code 我开始打算用此代码选择图像

Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);

and ononActivityResult 和ononActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            Uri selectedImageUri = data.getData();
            try {
                PickedImage= MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);

                nPostImage.setImageBitmap(PickedImage);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PickedImage.compress(Bitmap.CompressFormat.PNG, 100, baos);
                nPostImageBytes = baos.toByteArray();

            } catch (IOException e) {
                Toast.makeText(this,"Error Selecting Picture",Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }// if picking a picture
    }//if ok
}//On activity get result

and then I call this method that uploads the data to the database using volley 然后我调用此方法,使用齐射将数据上传到数据库

private void AddPost(final String UserID, final String UserType, final String nText, final byte[] nImage)
{
    final ProgressDialog loading=ProgressDialog.show(this,"please wait...","adding",false,false);

    String url="http://192.168.43.178/studentpool/add_post.php";

    StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            try {
                JSONObject jsonObject=new JSONObject(response);
                if(jsonObject.getInt(LoginActivity.TAG_SUCCESS)==1)
                {
                    loading.dismiss();
                    Toast.makeText(AddPostActivity.this,"Added Successfully",Toast.LENGTH_SHORT).show();

                    Intent intent=new Intent(AddPostActivity.this,MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                else
                {
                    loading.dismiss();
                    Toast.makeText(AddPostActivity.this,jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(AddPostActivity.this,"Error adding",Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("id",UserID);
            params.put("type",UserType);
            params.put("text",nText);
            params.put("image",Base64.encodeToString(nImage,Base64.DEFAULT));

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}//AddPost}

and this is my php code 这是我的PHP代码

<?php if($_SERVER['REQUEST_METHOD']=='POST'){
$id  = $_POST['id'];
$text= $_POST['text'];
$image=$_POST['image'];
$type=$_POST['type'];

require_once __DIR__ . '/db_config.php';

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);

$dt = new DateTime();
$dt->add(new DateInterval('PT3H'));

$result=mysqli_query($con,"INSERT INTO posts(user_id,text,post_image,date,type) VALUES ('$id','$text','$image','".$dt->format('Y-m-d h:i:s')."','$type')");

if ($result)
{

//success
$response["success"] = 1;

echo json_encode($response);

}
else
{
    $response["success"] = 0;
    $response["message"] = "Error adding the post";

    echo json_encode($response);
}}else{
$response["success"] = 0;
$response["message"] = "Missing required data";

// echo no users JSON
echo json_encode($response); }//no data ?>

I tried changing the post_image type to mediumtext to see what is getting stored in the database 我尝试将post_image类型更改为中文字,以查看数据库中存储了什么

and the images that works fine (the ones uploaded from the interface) have this kind of format 并且效果很好的图片(从界面上传的图片)具有这种格式

ÿØÿà?JFIFÿÛC... FØÿà?JFIFÿÛC...

the one uploaded from the app has this format 从应用上传的视频具有这种格式

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD.. / 9j / 4AAQSkZJRgABAQAAAQABAAD / 2wBD ..

I tried encoding the image before storing it in the database but I got an JSONexception 我尝试在将图像存储到数据库之前对其进行编码,但是得到了JSONexception

please help if you know anything about this 如果您对此有所了解,请提供帮助

and sorry for the long question... 对于这个长期的问题感到抱歉...

Thanks for your time 谢谢你的时间

I think if you add "data:image/png;base64," before your Base64 string, your problem might be solved. 我认为,如果在Base64字符串之前添加"data:image/png;base64," ,则可能会解决您的问题。 So try this: 所以试试这个:

params.put("image", "data:image/png;base64," + Base64.encodeToString(nImage,Base64.DEFAULT));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM