【问题标题】:How to save image through capturing in android to php?如何通过在android中捕获将图像保存到php?
【发布时间】:2015-02-17 05:48:29
【问题描述】:

我们已经为 android 和 php 尝试过这段代码。请看下面的代码。

安卓

Scn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                        // Open default camera
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                // start the image capture Intent
                startActivityForResult(intent, 100);
            }
 }
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 100 && resultCode == RESULT_OK) {


                 selectedImage = intent.getData();
                    imageBitmap = (Bitmap) intent.getExtras().get("data");

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);

                imageView1.setImageBitmap(imageBitmap);

                byte[] imageBytes = baos.toByteArray();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

               submitData(encodedImage);         
           }
}

public void submitData(final  String encodedImage) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //Looper.prepare();
                        Log.d("looper", "-->>>>");
                        try 
                        {
                            isAuthorized = isAuthenticated(encodedImage);
                        } 
                        catch (Exception e) 
                        {
                            Log.e("Exception ==> ", e.toString());  
                        }
                        MHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if(isAuthorized){
                                        if(AuthenticationResultJSONObject!=null){
                                            String message = AuthenticationResultJSONObject.getString("message");

                                            if(AuthenticationResultJSONObject.getString("status").equalsIgnoreCase("1"))
                                            {
                                                Toast.makeText(ScannerActivity.this,message,Toast.LENGTH_SHORT).show();
                                            }
                                            else if (AuthenticationResultJSONObject.getString("status").equalsIgnoreCase("0"))
                                            {
                                                Toast.makeText(ScannerActivity.this,message,Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Toast.makeText(ScannerActivity.this, "Loing unsuccessfull, please try again !", Toast.LENGTH_SHORT).show();
                                    }
                                } 
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                    Log.e("Exception 146==> ", e.toString());  
                                }
                                finally 
                                {

                                    //progressdialog.dismiss();
                                    //progress.dismissProgressDialog();
                                }
                            }
                        });
                    } catch (Exception e) {
                        Log.e("Exception 153==> ", e.toString());  
                    }
                }
            }).start();

        } catch (Exception e) {
            Log.e("Exception 159==> ", e.toString());  
        }
    }
    public boolean isAuthenticated(final  String encodedImage) 
    {
        isAuthorized = false;
        String encoder1 = "";
        final String url="http://bestpeopleservice.com/projects/scanner/api/api/api.php?class=login&method=login_data&json=";


        String finalurl = "{\"data\":{\"qr_code\":\""+username1+"\",\"user_pass\":\""+password1+"\",\"longitude\":\""+longitude1+"\",\"latitude\":\""+latitude1+"\",\"adderss\":\""+adderss1+"\",\"images\":\""+encodedImage+"\"}}";//
        Log.v("267 1111111", "done url -> "+url+finalurl);

        try {
            encoder1 = URLEncoder
                    .encode(finalurl,"UTF-8");
            Log.v("267 222", "done url 2 -> "+url+encoder1);
        } 
        catch (UnsupportedEncodingException e1)
        {
            e1.printStackTrace();
        }
                try {

                    if (isNetworkConnected()) {

                        AuthenticationResultJSONObject = new JSONObject(doFetchDataFromWebService_Simple_OnlyJSONResponse(url+encoder1));    

                        Log.v("Online", "User json array    ===  "+AuthenticationResultJSONObject);  

                    }else{

                        Toast.makeText(ScannerActivity.this, "Please check your internet connection and try again.", Toast.LENGTH_SHORT).show();

                    }
                }
                catch(Exception e){ 
                    e.getMessage();
                }
                finally{
                    if(AuthenticationResultJSONObject!=null){
                        isAuthorized = true;
                    }
                    else
                    {
                        isAuthorized=false;
                    }
                }
        //  }
    //  });
        return isAuthorized;
    }

    // Checking the internet connection
    public boolean isNetworkConnected() {
        ConnectivityManager connectivitymanagar = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo = connectivitymanagar.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isConnectedOrConnecting()) {
            return false;
        } else {
            return true;
        }
    }



    public String doFetchDataFromWebService_Simple_OnlyJSONResponse(
            String WebServiceURL) {

        String responseBody = "";
        JSONObject jobj = new JSONObject();
        try {
            HttpGet WSHttpPost = null;
            HttpClient WSHttpClient = null;
            HttpResponse WSHttpResponse = null;

            WSHttpClient = getNewHttpClient();
            WSHttpPost = new HttpGet(WebServiceURL);
            WSHttpResponse = WSHttpClient.execute(WSHttpPost);

            Log.d("resp", ""+WSHttpResponse);
            //responseBody = EntityUtils.toString(WSHttpResponse.getEntity());
            responseBody = EntityUtils.toString(WSHttpResponse.getEntity(), "UTF-8");


            Log.v("response1", "" + responseBody);

        } catch (Exception e) {
            Log.e("Exception2 ==> ", e.toString());
        }
        if (responseBody == null || responseBody.equalsIgnoreCase("null")) {
            return "";
        } else {
            return responseBody;
        }
    }

    public HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore
                    .getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                    params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

    public class MySSLSocketFactory extends SSLSocketFactory {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        public MySSLSocketFactory(KeyStore truststore)
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException {
            super(truststore);

            TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };

            sslContext.init(null, new TrustManager[] { tm }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host,
                    port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
}

它返回解析字节串。它的值太长了。

PHP

 $base=$Data['images'];
 $binary=base64_decode($base);
 header('Content-Type: bitmaps; charset=utf-8');
 header("Content-Length: " . mb_strlen($base, '8bit'));
 $file = fopen('qr_code.jpeg', 'wb');
 fwrite($file, $binary);
 fclose($file);
 echo 'Image upload complete!!, Please check your php file directory';

上面的代码正在运行。但它有一些问题。图像保存在文件夹中成功,但图像将显示为损坏。我们如何解决这个问题。

提前致谢。

【问题讨论】:

  • 将该图像保存在某个文件夹中
  • 默认保存在我们的根目录下。但它会以损坏的格式显示。

标签: java php android bitmap bytearray


【解决方案1】:

请试试这个代码,这个代码对我有用。

<?php

// Path to move uploaded files
$target_path = "uploads/";

// array for final json respone
$response = array();

// getting server ip address
$server_ip = gethostbyname(gethostname());

// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . '/xyz/' . '/' . $target_path;


if (isset($_FILES['image']['name'])) {
    $target_path = $target_path . basename($_FILES['image']['name']);

    // reading other post parameters
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $website = isset($_POST['website']) ? $_POST['website'] : '';

    $response['file_name'] = basename($_FILES['image']['name']);
    $response['email'] = $email;
    $response['website'] = $website;

    try {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }

        // File successfully uploaded
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
    } catch (Exception $e) {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} else {
    // File parameter is missing
    $response['error'] = true;
    $response['message'] = 'Not received any file!F';
}

// Echo final json response to client
echo json_encode($response);
?>

【讨论】:

    【解决方案2】:

    您好,我已使用此方法保存 myImage。

    • 在您的根目录中创建图像文件夹。

      $allowedExts = array("gif", "jpeg", "jpg", "png");

      $temp = explode(".", $_FILES["file"]["name"]);

      $extension = end($temp);

      move_uploaded_file($_FILES["file"]["tmp_name"], "../images/" . $varFileName);

    • 使用此 URL 下载我的代码以将图像文件发送到 php 服务器。

    https://onedrive.live.com/redir?resid=D6874F5E96BBF5A8!17174&authkey=!AIA5xGcRI7UnyNg&ithint=folder%2cjar

         final Dictionary<String, String> dictionary = new Hashtable<String, String>();
         dictionary.put("name", "kruti");
         dictionary.put("file", "file");
    

    【讨论】:

    • 你为什么使用 HTTP_GET ,使用 HTTP POST 。
    • 我们已经尝试过您的代码。但它没有发送任何响应,并且图像也没有保存在文件夹中。
    【解决方案3】:

    我不是 Android 开发者。

    但我知道问题出在您的请求上。您在 GET 请求方法中传递所有数据(在 URL 中附加参数)。但它有 2,083 个字符长度的限制。 (实际上取决于网络服务器)

    所以,如果您的图片尺寸高于此尺寸,它将简单地从 URL 截断。

    对于解决方案,您必须使用POST请求将数据提交给webservice。

    安卓

    android代码sn-p参考this question的答案

    PHP 代码

    <?php
    
    $json=json_decode($_POST['json']); //decoding json which is received from Android.
    
    $photo=$json->images; //get image data (which is encoded in base64)
    
    /* Decoding image */
    $binary = base64_decode ( $photo );
    
    /* Opening image */
    $file = fopen ( 'file_name_to_create.jpeg', 'wb' );
    
    /* Writing to server */
    fwrite ( $file, $binary );
    
    /* Closing image file */
    fclose ( $file );
    
    ?>
    

    它将在当前目录中创建file_name_to_create.jpeg

    参考

    1. Maximum Length of GET request
    2. POST request using Android

    【讨论】:

    • @kruti,我猜问题出在 URL 编码上。我建议您从 php 中回显您的数据,并将其记录在 android logcat 中。在您的问题中发布编码图像。
    • @kruti 你把 GET 方法改成 POST 了吗?
    • 我们已经尝试过使用 post 方法。但它将图像保存在文件夹中但文件大小为0。
    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多