【问题标题】:Image not inserted from android to MySQL图像未从 android 插入 MySQL
【发布时间】:2016-02-04 07:30:16
【问题描述】:

我真的需要帮助!!

我使用下面的代码从图库中获取图像,最后将其插入到MySQLphp。图片会从Activity B中获取,最后返回Activity A,点击Activity A中的按钮后保存到MySQL中。

活动 B

 Uri selectedImage;
 private Uri imageUri;
ImageView imageView;

     private void activeGallery() {
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, RESULT_LOAD_IMAGE);
        }


  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_LOAD_IMAGE:
                if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
                    selectedImage = data.getData();
                    imageView.setImageURI(selectedImage);
                }

                break;

 submit.setOnClickListener(new View.OnClickListener() { // back to Activity A
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                amount = Amount.getText().toString();
                description = Description.getText().toString();
                type = spinnerType.getSelectedItem().toString();
                returnIntent.putExtra("type", type);
                returnIntent.putExtra("description", description);
                returnIntent.putExtra("amount", amount);
                if(selectedImage!=null) {
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                }
                else
                {
                    returnIntent.putExtra("img_uri", Uri.parse("android.resource://com.example.project.myapplication/mipmap/no_image").toString());
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

Activity A(图片和文字可以从B返回到A)

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
        if (resultCode == RESULT_OK) {
            if (requestCode == PROJECT_REQUEST_CODE) {
                ReceiveType = data.getStringExtra("type");
                ReceiveDescription = data.getStringExtra("description");
                ReceiveAmount = data.getStringExtra("amount");
                imgURI = Uri.parse(data.getStringExtra("img_uri"));
                // Toast.makeText(getApplication(),ReceiveType+ReceiveAmount+ReceiveDescription+"",Toast.LENGTH_LONG).show();
                if (mClickedPosition == -1) {  // if icon clicked
                    if (obj != null)
                        obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
                     addOrRemoveFooter();

                } else {
                    if (obj != null)
                     obj.changeItem(mClickedPosition, ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
                }
            }
        }
    }

这里是有趣的部分。当Activity A中的提交按钮被点击时

 public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) {
            JSONArray jsonArray = new JSONArray();
            try {
                for (ImageAndText i : listItems) {
                    JSONObject object = new JSONObject();
                    String type = i.getType();
                    String[] Type = type.split(":");
                    object.put("type", Type[1]);
                   // Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show();
                    String amount = i.getAmount();
                    String[] Amount = amount.split(":");
                    object.put("amount", Amount[1]);
                    String description = i.getDescription();
                    String[] Description = description.split(":");
                    object.put("description", Description[1]);
                    String image=i.getImage().toString();
                    Uri imageUri = Uri.parse(image);
                    object.put("image", image);
                    object.put("ts_id", id);
                    object.put(Configs.KEY_IMAGE,getStringImage(imageUri));
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            AddStaff ru = new AddStaff(jsonArray);
            ru.execute();

        }

        class AddStaff extends AsyncTask<String, Void, String> {
            ProgressDialog loading;

            JSONArray jsonArray;

            AddStaff(JSONArray jsonArray) {
                this.jsonArray = jsonArray;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true);
            }

            @Override
            protected String doInBackground(String... params) {
                try {
                    HashMap<String, String> data = new HashMap<String, String>();
                    data.put("listItems", jsonArray.toString());
                    //Log.d("log", "This json = " + jsonArray.toString());
                    RequestHandler rh = new RequestHandler();
                    String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
                    return result;
                } catch (Exception e) {
                    return "";
                }
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                //Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
            }
        }


        public String getStringImage(Uri imgUri) {

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                return encodedImage;
            } catch (Exception e) {
            }

            return "";
        }
    }

我在这里做了很多测试。如果所选图像来自downloadwhatsapp,则可以插入。如果我从 My photos 中选择图像,则不会插入图像。为什么会这样???

SaffBenefit.php

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        if( !empty( $_POST['listItems'] ) ){
            $listItems = json_decode( $_POST['listItems'], true ); 
            $mysqli = new mysqli("localhost", "spiral69_wp178", "q1w2e3r4", "spiral69_androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
            $sql="INSERT INTO `staff_benefit` 
                 ( `type`, `amount`, `description`, `image`, `ts_id` ) 
                  VALUES ( ?, ?, ?, ?, ? )";
            if($stmt=$mysqli->prepare($sql )){
                $url="http://www.ss.com/Android/CRUD/PhotoUpload/";
                foreach( $listItems as $item ){ 
                    $id = uniqid();
                    $image_name = $id.".png";
                    $save_path = 'PhotoUpload/'.$image_name;
                    $image_url = $url.$image_name;
                    $bytes=file_put_contents($save_path, base64_decode($item['image']));
                    if( !$bytes ){
                        echo 'Error saving image';  
                    }else{
                        $stmt->bind_param('sssss', 
                        $item['type'], 
                        $item['amount'], 
                        $item['description'], 
                        $image_url, 
                        $item['ts_id'] );
                        if( !$res=$stmt->execute()){ 
                            echo 'Query failed with code: '.$stmt->errno;
                        }
                    }
                } 
            }
            $mysqli->close();
        }
    }
?>

【问题讨论】:

  • My photos选择图片时有没有看到异常
  • 你的意思是我需要添加 try catch 吗?
  • 不,我问的是当您尝试从本地存储插入照片时,是否有任何异常?看起来您遇到了 OutOfMemory 异常。请确认。
  • @MustansarSaeed 没有显示异常
  • @MustansarSaeed 我可以使用 try and catch 来确认吗?

标签: android mysql image android-studio android-image


【解决方案1】:

可能存在base64 encode data 太高的问题,您发送到服务器时MySql 无法处理。您应该做的是将压缩值更改为70%bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    检查您是否已在清单文件中授予写入外部存储权限。当您尝试将副本发送到服务器时,单独读取不起作用。

    【讨论】:

    • 我有
    猜你喜欢
    • 2019-05-23
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多