使用Android将图像发送到MySQL数据库
我有一个从MySQL数据库发送和检索数据的当前应用程序,但到目前为止我传输的信息是字符串。我如何更新下面的代码,以便也能发送图像使用Android将图像发送到MySQL数据库,android,mysql,json,Android,Mysql,Json,我有一个从MySQL数据库发送和检索数据的当前应用程序,但到目前为止我传输的信息是字符串。我如何更新下面的代码,以便也能发送图像 public class NewProductActivity extends Activity { // Progress Dialog private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputPrice
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();
}
}
}
公共类NewProductActivity扩展活动{
//进度对话框
私人对话;
JSONParser JSONParser=新的JSONParser();
编辑文本输入名;
编辑文本输入价格;
编辑文本输入描述;
编辑文本输入;
按钮btntakphoto;
ImageView imgTakenPhoto;
专用静态最终内部凸轮需求=1313;
//创建新产品的url
私有静态字符串url\u创建\u产品=”http://buiud.com/android_connect/create_product.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add_产品);
//编辑文本
inputName=(EditText)findViewById(R.id.inputName);
inputPrice=(EditText)findViewById(R.id.inputPrice);
inputDesc=(EditText)findViewById(R.id.inputDesc);
inputImg=(EditText)findViewById(R.id.imageView1);
//创建按钮
按钮btnCreateProduct=(按钮)findViewById(R.id.btnCreateProduct);
//按钮点击事件
btnCreateProduct.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//在后台线程中创建新产品
新建CreateNewProduct().execute();
}
});
btnTakePhoto=(按钮)findViewById(R.id.button1);
imgTakenPhoto=(ImageView)findViewById(R.id.imageView1);
setOnClickListener(新的btnTakePhotoClicker());
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
//TODO自动生成的方法存根
super.onActivityResult(请求代码、结果代码、数据);
if(请求代码==CAM_请求列表){
位图缩略图=(位图)数据.getExtras().get(“数据”);
imgTakenPhoto.setImageBitmap(缩略图);
}
}
类btnTakePhotoClicker实现Button.OnClickListener
{
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
Intent cameraIntent=newintent(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
startActivityForResult(Camerainent,CAM_Requirest);
}
}
/**
*创建新产品的后台异步任务
* */
类CreateNewProduct扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(NewProductActivity.this);
pDialog.setMessage(“创建产品…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创造产品
* */
受保护的字符串doInBackground(字符串…args){
字符串名称=inputName.getText().toString();
字符串价格=inputPrice.getText().toString();
字符串描述=inputDesc.getText().toString();
字符串image=inputImg.getText().toString();
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“名称”),名称);
参数添加(新的BasicNameValuePair(“价格”,价格));
参数添加(新的BasicNameValuePair(“说明”,说明));
添加(新的BasicNameValuePair(“图像”,图像));
//获取JSON对象
//请注意,创建产品url接受POST方法
JSONObject json=jsonParser.makeHttpRequest(url\u create\u product,
“POST”,params);
//检查cat fro响应日志
d(“创建响应”,json.toString());
//检查成功标签
试一试{
int success=json.getInt(TAG_success);
如果(成功==1){
//已成功创建产品
Intent i=新Intent(getApplicationContext(),AllProductsActivity.class);
星触觉(i);
//关闭此屏幕
完成();
}否则{
//未能创建产品
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//完成后关闭对话框
pDialog.disclose();
}
}
}
注意:我像添加其他字符串字段一样添加了图像字段,但是应用程序现在停止了,它显然无法将图片转换为文本。让我知道你的想法,或任何类型的铸造可用。我只拍了一张照片,照片将被发送到MySQL。如果您想在服务器上发送图像!你必须在字符串中更改它 用于将其保存在数据库中!你必须把它转换成类型 请尝试以下代码:
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));
我希望这会有帮助!请参阅此处了解更多详细信息。将图像路径存储在数据库中您可以将照片保存在设备的外部或内部内存中,并将路径保存在MySQL数据库中。代码示例将非常有用。数据库字段中的LongBlob为img,但我如何更改上面的代码,现在,它实际上是一个布局的类型视图。似乎可以工作,但我得到的唯一错误是;类型base64EncodeBytes(byte[])的方法未定义。我正在调用OnCreate(Bundle…)函数中的第一部分代码,这样做正确吗?Ops!我已经更新了我的答案!它是encodeToString(字节[],标志);谢谢你,我快到了,谢谢你的帮助。最后一个帮助,你能在我的代码上完全实现吗?