如何使用php将使用android中的摄像头拍摄的图像存储到数据库中

时间:2017-02-02 10:07:47

标签: php android android-volley

我在活动中有两个按钮,一个用于获取相机,另一个用于将图像上传到服务器。我在android中使用了齐射来执行此操作。它显示如下错误

E/AndroidRuntime: FATAL EXCEPTION: Thread-2147
                                                                       java.lang.OutOfMemoryError
                                                                           at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
                                                                           at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
                                                                           at java.lang.StringBuilder.append(StringBuilder.java:124)
                                                                           at libcore.net.UriCodec.appendEncoded(UriCodec.java:119)
                                                                           at libcore.net.UriCodec.encode(UriCodec.java:133)
                                                                           at java.net.URLEncoder.encode(URLEncoder.java:57)
                                                                           at com.android.volley.Request.encodeParameters(Request.java:450)
                                                                           at com.android.volley.Request.getBody(Request.java:436)
                                                                           at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)
                                                                           at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
                                                                           at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
                                                                           at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
                                                                           at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

当我点击上传按钮。相机按钮工作正常。我的android如下:

Image.java

package com.login.sowmy.uspcar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Image extends AppCompatActivity {
    Button btnimgupload, btncamera;
    ImageView imgliccard;
    private String encoded_string, cust_name;
    private Bitmap bitmap;
    private File file;
    private Uri file_uri;
    private static final int CAMERA_REQUEST = 1888;
    SharedPreferences shared;
    final String TAG = this.getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        imgliccard = (ImageView) findViewById(R.id.imglic);
        btncamera = (Button) findViewById(R.id.btncamera);
        btnimgupload = (Button) findViewById(R.id.btnupload);
        shared = getSharedPreferences("get", Context.MODE_PRIVATE);
        cust_name = shared.getString("key", null);
        btncamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                getFileUri();
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);

            }
        });
        btnimgupload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Encode_image().execute();
            }
        });
    }



    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getExtras().get("data");
            imgliccard.setImageURI(file_uri);

        }
    }


    public void getFileUri() {
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
                File.separator + cust_name + ".jpg");
        file_uri = Uri.fromFile(file);

    }

    public class Encode_image extends AsyncTask<Void, Void, Void> {
        @Override

        protected Void doInBackground(Void... params) {
            bitmap = BitmapFactory.decodeFile(file_uri.getPath());
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] array = stream.toByteArray();
            encoded_string = Base64.encodeToString(array, 0);
            System.out.print("Step 1" +encoded_string);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            makeRequest();
        }
    }


    private void makeRequest() {
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        StringRequest request=new StringRequest(Request.Method.POST, "http://localhost/img_upload1.php", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "error",Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map=new HashMap<>();
                map.put("encoded_string",encoded_string);
                map.put("cust_name",cust_name);
                return map;
            }
        };
        requestQueue.add(request);
    }
}

我的php文件如下

<?php
header('Content-type : bitmap; charset=utf-8');

if(isset($_POST["encoded_string"])) {
    $encoded_string=$_POST["encoded_string"];
    $cust_name=$_POST["cust_name"];
    $decoded_string =base64_decode($encoded_string);
    $path= 'android/'.$cust_name;

    $file=fopen($path,'wb');
    $is_written=fwrite($file,$decoded_string);
    fclose($file);

    if($is_written >0) {
        require 'connect.php';
        $query = "UPDATE cust_detail SET img_url=? WHERE cusname=? ";
        $params=array($path,$cust_name);
        $result = sqlsrv_query($conn,$query,$params);
        if( $result === false) {  
            echo "Error in query preparation/execution.\n";  
            die( print_r( sqlsrv_errors(), true));  
        } else {
            echo "success";
        }
    }
    sqlsrv_close($conn);
}
?>

我在清单文件中添加了以下内容

<uses-feature
    android:name="android.hardware.camera2"
    android:required="true" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

我在build gradle中添加了如下所示的凌空

compile 'com.android.volley:volley:1.0.0'.

任何人都可以帮助我如何使用PHP脚本使用凌空上传图像?

0 个答案:

没有答案