【问题标题】:Android application to send image to MySQL将图像发送到 MySQL 的 Android 应用程序
【发布时间】:2014-02-13 15:45:42
【问题描述】:

我有一个 android 应用程序,它将图像发送到我的数据库;

public class NewProductActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;
public String image_str;
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);

    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();
    image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);


    // 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_str = 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("img",image_str));
        //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();
    }

}
}

即使我希望图像为 .png,但它在数据库中显示为 .bin,我该如何更改它,我已经阅读了有关在应用程序调用 create.php 但没有雪茄时输入内容的信息。我什至无法在 HTML 页面上将 .bin 显示为图像。

【问题讨论】:

  • 可以使用HttpPost上传图片吗?
  • 也许这就是应用在上传后一直崩溃的原因?
  • 请发布您的日志。
  • 它不再崩溃了,这是一个 PHP 问题,谢谢
  • @raklar.. 你能发布 php 代码吗?它也会帮助我。我也在寻找将图像从 android 应用程序发送到 mysql 的代码。

标签: php android mysql base64


【解决方案1】:
  <?php 
    $name = $_POST['image'];
     $entry = base64_decode($name);
     $image = imagecreatefromstring($entry);
     $directory = dirname(__FILE__).DIRECTORY_SEPARATOR."images/".DIRECTORY_SEPARATOR."index".$title.".jpeg";
     header ( 'Content-type:image/jpeg' );
     $imagetojpg=imagejpeg($image, $directory); 
     imagedestroy($image );      
     readfile ($directory);  
     exit ();
    ?>

这应该可以正常工作。image 是一个包含 base64 编码字符串的变量。

【讨论】:

    【解决方案2】:

    由于您的图片是使用 Base64 编码的,您需要在服务器端对其进行解码并将其保存为 PNG 文件。

    <?php 
    $decoded=base64_decode($encodedString);    
    file_put_contents('newImage.PNG',$decoded);
    ?>
    

    http://php.net/fr/base64_decode

    【讨论】:

    • $encodedString 我的 MySQL 变量是 $img 吗?当我更新我的数据库或从中检索时也会使用它吗?非常感谢!
    • 看来您是在Mysql 中存储字符串结尾的图像,对吧?那么Mysql将其存储为二进制文件是正常的,您的工作是在将二进制文件显示为PNG图像之前对其进行解码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2016-02-13
    相关资源
    最近更新 更多