【问题标题】:How to upload a captured image with android device to mysql database using php?如何使用 php 将使用 android 设备捕获的图像上传到 mysql 数据库?
【发布时间】:2013-09-21 10:43:19
【问题描述】:

我是 android 新手,我正在尝试将图像上传到 mysql 服务器。在我的应用程序中,当用户单击按钮时,我有一个名为上传图像的按钮,它将在 android 设备中打开一个摄像头。我在 imageview 中使用相机成功获取了捕获的图像,我想使用 php 将此图像保存在 mysql 数据库中,我已使用 php 成功连接到数据库并上传了在 edittext 中输入的几个字段,但我无法上传图像。我用谷歌搜索了它,但都显示了带有 url 的上传图片。但在我的情况下,我的代码略有不同,请帮助我。

FormActivity.java

public class FormActivity extends Activity {

final Context context = this;
private ProgressDialog pDialog;
static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
private static String url_submit_hourly = "http://www.example.com/FacebookApp/submit.php";

EditText tasktitle;

String title;
Button upload, submit;

private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
byte[] byteArray;
protected static final int TAKE_PHOTO_CODE = 0;
byte[] imgbyte;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.submit_hourly);

    tasktitle = (EditText) findViewById(R.id.etfirst);

    submit = (Button) findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new BookSlot().execute();
        }
    });

    upload = (Button) findViewById(R.id.upload);
    this.imageView = (ImageView) this.findViewById(R.id.image);
    upload.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(intent, CAMERA_REQUEST);
        }

    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);

    }

}

class BookSlot extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(FormActivity.this);
        pDialog.setMessage("Creating Hourly..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {


        title = tasktitle.getText().toString();


        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("task_tilte", title));

        JSONObject json = jsonParser.makeHttpRequest(url_submit_hourly,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                Intent i = new Intent(getApplicationContext(),
                        FacebookLoginActivity.class);

                startActivity(i);

                // closing this screen
                finish();
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

}

提交.php

<?php


// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['task_tilte'])) {

$title = $_POST['task_tilte'];


// include db connect class
define('__ROOT__', dirname(dirname(__FILE__))); 
require_once(__ROOT__.'/FacebookApp/db_connect.php'); 

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO                       task_table(task_tilte)     VALUES('$title')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

我不知道如何将 imageview 中的图像保存到 mysql 数据库。

【问题讨论】:

    标签: php android mysql image


    【解决方案1】:

    试试这个:

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
                byte [] byte_arr = stream.toByteArray();
                String image_str = Base64.encodeBytes(byte_arr);
                ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
    
                nameValuePairs.add(new BasicNameValuePair("image",image_str));
    
                 Thread t = new Thread(new Runnable() {
    
                @Override
                public void run() {
                      try{
                             HttpClient httpclient = new DefaultHttpClient();
                             HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
                             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                             HttpResponse response = httpclient.execute(httppost);
                             String the_string_response = convertResponseToString(response);
                             runOnUiThread(new Runnable() {
    
                                    @Override
                                    public void run() {
                                        Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                                    }
                                });
    
                         }catch(Exception e){
                              runOnUiThread(new Runnable() {
    
                                @Override
                                public void run() {
                                    Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                              
                                }
                            });
                               System.out.println("Error in http connection "+e.toString());
                         }  
                }
            });
             t.start();
    
    
    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
    
                 String res = "";
                 StringBuffer buffer = new StringBuffer();
                 inputStream = response.getEntity().getContent();
                 int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
                  runOnUiThread(new Runnable() {
    
                @Override
                public void run() {
                    Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                     
                }
            });
    
                 if (contentLength < 0){
                 }
                 else{
                        byte[] data = new byte[512];
                        int len = 0;
                        try
                        {
                            while (-1 != (len = inputStream.read(data)) )
                            {
                                buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                            }
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        try
                        {
                            inputStream.close(); // closing the stream…..
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        res = buffer.toString();     // converting stringbuffer to string…..
    
                        runOnUiThread(new Runnable() {
    
                        @Override
                        public void run() {
                           Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                        }
                    });
                        //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
                 }
                 return res;
            }
    

    【讨论】:

    • 嗨@shruti 感谢您的回答,但是一旦我已经有了 json 解析器类并成功插入标题,请查看我的代码,并且我正在从这个 imageview 获取 imageview 中的图像,我想将图像上传到服务器使用现有的 json 类。可能我需要将图像位图转换为字符串。请查看我的代码一次
    • 是的,您需要使用上述函数将图像转换为字符串。
    • 我已经更改了我的代码并尝试仍然在受保护的数据库中显示空值 void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {位图照片 = (位图) data.getExtras().get("data"); imageView.setImageBitmap(照片); ByteArrayOutputStream baos = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.PNG, 100, baos);字节[] b = baos.toByteArray(); image_str = Base64.encodeToString(b, Base64.DEFAULT); } } 和 params.add(new BasicNameValuePair("image", image_str));
    【解决方案2】:

    尝试将图像转换为 base_64,然后发送到 PHP 以将其存储在 MySQL 中,当从 MySQL 读取图像时,您需要对其进行解码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2013-07-17
      • 2016-05-29
      • 2015-01-01
      • 1970-01-01
      • 2011-04-21
      • 2015-09-18
      相关资源
      最近更新 更多