使用Android将图像发送到MySQL数据库 [英] Sending Image to the MySQL database with Android

查看:104
本文介绍了使用Android将图像发送到MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有当前的应用程序,该应用程序可以从MySQL数据库发送和检索数据,但是到目前为止我传递的信息是String.如何更新下面的代码以也可以发送图像.

public class NewProductActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
EditText inputImg;
Button btnTakePhoto;
ImageView imgTakenPhoto;
private static final int CAM_REQUREST = 1313;
// url to create new product
private static String url_create_product = "http://buiud.com/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

    // Edit Text
    inputName = (EditText) findViewById(R.id.inputName);
    inputPrice = (EditText) findViewById(R.id.inputPrice);
    inputDesc = (EditText) findViewById(R.id.inputDesc);
    inputImg = (EditText) findViewById(R.id.imageView1);
    // Create button
    Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

    // button click event
    btnCreateProduct.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new product in background thread
            new CreateNewProduct().execute();
        }
    });
    btnTakePhoto = (Button) findViewById(R.id.button1);
    imgTakenPhoto = (ImageView) findViewById(R.id.imageView1);

    btnTakePhoto.setOnClickListener(new btnTakePhotoClicker());

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == CAM_REQUREST) {
          Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
          imgTakenPhoto.setImageBitmap(thumbnail);
      }
}

class btnTakePhotoClicker implements Button.OnClickListener
{
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAM_REQUREST);
    }
}
/**
 * Background Async Task to Create new product
 * */
class CreateNewProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
        String name = inputName.getText().toString();
        String price = inputPrice.getText().toString();
        String description = inputDesc.getText().toString();
        String image = inputImg.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("price", price));
        params.add(new BasicNameValuePair("description", description));
        params.add(new BasicNameValuePair("image", image));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "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(), AllProductsActivity.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();
    }

}
}

注意:我已经像其他String字段一样添加了image字段,但是应用程序现在停止了,它显然无法将图片转换为Text.让我知道您的想法或任何可用的转换.我只拍了一张照片,然后将该照片发送到MySQL.

解决方案

如果要在服务器上发送图像!您必须在 Base 64 字符串中进行更改. >

用于将其保存在数据库中!您必须在 Blob 输入!

尝试此代码:

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);          
        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.encodeToString(byte_arr, Base64.DEFAULT);

并将其作为参数传递,就像您在请求中添加其他参数一样!

params.add(new BasicNameValuePair("image",image_str));

我希望这会有所帮助!有关更多详细信息,请参见此链接.

I have the current application which sends and retrieves data from a MySQL database but the information so far I was transferring was String. How can I update the code below to be able to send images too.

public class NewProductActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
EditText inputImg;
Button btnTakePhoto;
ImageView imgTakenPhoto;
private static final int CAM_REQUREST = 1313;
// url to create new product
private static String url_create_product = "http://buiud.com/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

    // Edit Text
    inputName = (EditText) findViewById(R.id.inputName);
    inputPrice = (EditText) findViewById(R.id.inputPrice);
    inputDesc = (EditText) findViewById(R.id.inputDesc);
    inputImg = (EditText) findViewById(R.id.imageView1);
    // Create button
    Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

    // button click event
    btnCreateProduct.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new product in background thread
            new CreateNewProduct().execute();
        }
    });
    btnTakePhoto = (Button) findViewById(R.id.button1);
    imgTakenPhoto = (ImageView) findViewById(R.id.imageView1);

    btnTakePhoto.setOnClickListener(new btnTakePhotoClicker());

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == CAM_REQUREST) {
          Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
          imgTakenPhoto.setImageBitmap(thumbnail);
      }
}

class btnTakePhotoClicker implements Button.OnClickListener
{
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAM_REQUREST);
    }
}
/**
 * Background Async Task to Create new product
 * */
class CreateNewProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
        String name = inputName.getText().toString();
        String price = inputPrice.getText().toString();
        String description = inputDesc.getText().toString();
        String image = inputImg.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("price", price));
        params.add(new BasicNameValuePair("description", description));
        params.add(new BasicNameValuePair("image", image));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "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(), AllProductsActivity.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();
    }

}
}

Note: I have added the image field as I did other String fields, but the application now stops, it can't convert the picture as Text obviously. Let me know what you think, or any sort of casting available. I just take a photo and that photo is to be sent to MySQL.

解决方案

If you want to send Image on Server! You have to change it in Base 64 string.

For saving it in Database! You have to convert it in Blob type!

try this code:

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);          
        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.encodeToString(byte_arr, Base64.DEFAULT);

And pass this as a parameter just like you are adding other parameters in request!

params.add(new BasicNameValuePair("image",image_str));

I hope this will help! See this link for further detail.

这篇关于使用Android将图像发送到MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆