php - 从 Android 手机上传图片到笔记本电脑需要太长时间,最后上传时显示“Windows 照片查看器无法显示,因为文件为空”

标签 php android wamp

我正在尝试开发基于相机的方程式求解器,它需要使用 wamp 将相机点击的图像上传到本地服务器。这是我的 android 代码。它有两个按钮,一个用于上传手写方程式相机图像,另一个用于上传打印的方程式相机图像。根据按下的按钮,将从我的笔记本电脑执行一个特定的 .php 文件,以将上传的图像存储在 c:/wamp/www/upload 的文件夹中。目前我正在测试带有手写方程图像按钮的上传部分。

封装 EqSolver.example;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;

public class EqSolverActivity extends Activity {

    private SurfaceView m_Preview = null;
    private SurfaceHolder m_PreviewHolder = null;
    private Camera m_Camera = null;
    private Builder m_Builder;
    private Button m_QueryButton = null;
    private int m_QueryType;

    public static final String QUERY_IMAGE_1 = "query_image_1";
    public static final String QUERY_IMAGE_2 = "query_image_2";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* Use full screen and remove window title */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        /* Create message dialog for showing text */
        m_Builder = new AlertDialog.Builder(this);
        m_Builder.setTitle("Solution");

        /* Class to take care of the photo application */
        m_Preview = (SurfaceView) findViewById(R.id.SurfaceView01);
        m_PreviewHolder = m_Preview.getHolder();
        m_PreviewHolder.addCallback(surfaceCallback);
        m_PreviewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        /* Add button for query/add */
        m_QueryButton = (Button) findViewById(R.id.solveHW);
        m_QueryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_QueryType = 1;
                takePicture();
            }
        });
        m_QueryButton = (Button) findViewById(R.id.solveP);
        m_QueryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_QueryType = 0;
                takePicture();
            }
        });

        m_QueryButton = (Button) findViewById(R.id.confirm);
        m_QueryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                TextView editView = (TextView) findViewById(R.id.equation);
                Button button = (Button) findViewById(R.id.confirm);
                Log.v("Final Equation: ", editView.getText().toString());
                editView.setVisibility(View.INVISIBLE);
                button.setVisibility(View.INVISIBLE);
                byte[] imageBytes = editView.getText().toString().getBytes();
                ServerPushAsync mAsync = new ServerPushAsync(imageBytes, -1,
                        QUERY_IMAGE_2);
                mAsync.execute();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_CAMERA
                || keyCode == KeyEvent.KEYCODE_SEARCH) {
            m_QueryType = 0;
            takePicture();
            return (true);
        }
        return (super.onKeyDown(keyCode, event));
    }

    private void takePicture() {
        m_Camera.takePicture(null, null, photoCallback);
    }

    Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
        private Camera m_Camera;

        public void onPictureTaken(byte[] data, Camera m_Camera) {
            /* Downsize the image from the camera */
            Bitmap bImage = BitmapFactory.decodeByteArray(data, 0, data.length);
            bImage = Bitmap.createScaledBitmap(bImage, 640, 480, false);
            ByteArrayOutputStream oData = new ByteArrayOutputStream();
            bImage.compress(CompressFormat.JPEG, 85, oData);
            this.m_Camera = m_Camera;

            /* Query image */
            ServerPushAsync mAsync = new ServerPushAsync(oData.toByteArray(),
                    m_QueryType, QUERY_IMAGE_1);
            mAsync.execute();

        }
    };

    /*
     * COPY THE FOLLOWING FUNCTION TO YOUR CLASS IF YOU PLAN TO USE TEXT
     * RECOGNITION SERVICE
     */
    /* Send HTTP POST request with image data to image recognition server */
    public static String QueryImage1(byte[] bData, int iQueryType) {
        /* Setup http objects */
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost;
        if (iQueryType == 1) {
            httpPost = new HttpPost(
                    "http://192.168.1.5/EqSolverProcessWritten.php");
        } else {
            httpPost = new HttpPost(
                    "http://192.168.1.5/EqSolverProcessPrinted.php");
        }
        ByteArrayEntity bEntity = new ByteArrayEntity(bData);
        String sResult = null;

        try {
            /* Construct data */
            httpPost.setEntity(bEntity);
            /* Send HTTP request */
            HttpResponse httpResponse = httpClient.execute(httpPost);

            /* Get the text results from the response */
            BufferedReader hBufferedReader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuilder sInputBuffer = new StringBuilder();
            try {
                String sInputLine = null;
                while ((sInputLine = hBufferedReader.readLine()) != null)
                    sInputBuffer.append(sInputLine + "\n");
            } catch (Exception ex) {
            } finally {
                try {
                    httpResponse.getEntity().getContent().close();
                } catch (Exception ex) {
                }
            }
            sResult = sInputBuffer.toString();

            Log.v("RECEIVED", sResult);
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }
        return sResult;
    };

    public static String QueryImage2(byte[] bData) {
        /* Setup http objects */
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(
                "http://192.168.1.5/EqSolverSolve.php");
        String test = "THIS IS A TEST";
        ByteArrayEntity bEntity = new ByteArrayEntity(bData);

        String sResult = null;

        try {
            /* Construct data */
            httpPost.setEntity(bEntity);
            /* Send HTTP request */
            HttpResponse httpResponse = httpClient.execute(httpPost);

            /* Get the text results from the response */
            BufferedReader hBufferedReader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuilder sInputBuffer = new StringBuilder();
            try {
                String sInputLine = null;
                while ((sInputLine = hBufferedReader.readLine()) != null)
                    sInputBuffer.append(sInputLine + "\n");
            } catch (Exception ex) {
            } finally {
                try {
                    httpResponse.getEntity().getContent().close();
                } catch (Exception ex) {
                }
            }
            sResult = sInputBuffer.toString();

            Log.v("RECEIVED", sResult);
        } catch (Exception e) {
        }
        return sResult;
    };

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
        public void surfaceCreated(SurfaceHolder holder) {
            m_Camera = Camera.open();
            /* Set the camera parameters to take the smallest image as possible */
            Camera.Parameters currentParameters = m_Camera.getParameters();
            m_Camera.setParameters(currentParameters);
            try {
                m_Camera.setPreviewDisplay(m_PreviewHolder);
            } catch (Throwable t) {
                Log.e("PictureDemo-surfaceCallback",
                        "Exception in setPreviewDisplay()", t);
                Toast.makeText(EqSolverActivity.this, t.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            Camera.Parameters currentParameters = m_Camera.getParameters();
            currentParameters.setPreviewSize(width, height);
            currentParameters.setPictureFormat(PixelFormat.JPEG);
            m_Camera.setParameters(currentParameters);
            m_Camera.startPreview();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            m_Camera.stopPreview();
            m_Camera.release();
            m_Camera = null;
        }
    };

    /**
     * Asynchronous task ... Runs in background thread , does not block the UI
     */

    private class ServerPushAsync extends AsyncTask<String, String, String> {

        private byte[] bData;
        private int iQueryType;
        private String QueryImageType;
        private AlertDialog pg;

        public ServerPushAsync(byte[] bData, int iQueryType,
                String QueryImageType) {
            this.bData = bData;

            this.iQueryType = iQueryType;
            this.QueryImageType = QueryImageType;
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            pg = new ProgressDialog(EqSolverActivity.this);
            pg.setCancelable(false);
            ((ProgressDialog) pg)
                    .setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pg.setMessage("Pushing image to server...");
            pg.show();
        }

        protected String doInBackground(String... args) {
            String response = "";
            if (QueryImageType.equals(QUERY_IMAGE_1)) {
                response = EqSolverActivity.QueryImage1(bData, iQueryType);
            } else {
                // query_image_2
                response = EqSolverActivity.QueryImage2(bData);
            }

            return response;
        }

        @Override
        protected void onPostExecute(String response) {

            if (pg != null) {
                pg.dismiss();
            }
            if (response == null) {
                response = "something went wrong";
            }
            if (response.equals("")) {
                response = "something went wrong";
                Log.e("ERROR", "NO response captured");
            }

            if (QueryImageType.equals(QUERY_IMAGE_1)) {
                /* Display equation and wait for confirmation from user */
                TextView editView = (TextView) findViewById(R.id.equation);
                Button button = (Button) findViewById(R.id.confirm);
                editView.setText(response);
                editView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                m_Camera.startPreview();
            } else {
                TextView editView = null;
                // query_image_2
                m_Builder.setMessage((QueryImage2(editView.getText().toString()
                        .getBytes())));
                editView.setText("");
                m_Builder.show();
            }

        }
    }

}

这是我的 php 代码,用于处理手写方程。 EqSolverHandwritten.php

   <?php

$command = "del /F C:\wamp\www\upload\tessLineImg.txt"; 
exec($command);
$command = "del /F C:\wamp\www\upload\lineImgCorr.jpg";
exec($command);
$command = "del /F C:\wamp\www\upload\TessOutput.txt";
exec($command);
$command = "del /F C:\wamp\www\upload\svmOutput.txt";
exec($command);

/* Get input and configuration parameters */
$bData = file_get_contents('php://input');

/* Setup time stamp for different queries */
 $fCurrTime  = time(true); 
 $fJune01    = 1338447600;
 $fDiffSec   = $fCurrTime - $fJune01;
 $fHour      = floor( ($fDiffSec%86400)/3600);
 $fMinute    = floor( ($fDiffSec%3600)/60 );
 $sTimeStamp = sprintf('%02d%02d_%.0f', $fHour, $fMinute, $fDiffSec%10);

//$sTimeStamp = time();

/* Setup file names and upload paths */
$sInputFileJpg      = './inputImg_'.$sTimeStamp.'.jpg';
$photo_upload_path  = './upload/'.$sInputFileJpg;

/* Save the uploaded jpg image to file */
file_put_contents( $photo_upload_path, $bData);

?>

最佳答案

我终于解决了这个错误,想在很长一段时间后将其发布在这里。我只需要关闭我的防火墙,它就像魔术一样工作:D!

关于php - 从 Android 手机上传图片到笔记本电脑需要太长时间,最后上传时显示“Windows 照片查看器无法显示,因为文件为空”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30973158/

相关文章:

javascript - XmlHttpRequest POST 数据为空

android - 布局权重在 ScrollView 中不起作用

mysql - 警告 : mysql_query(): MySQL server has gone away

php - fatal error : Call to undefined function ldap_connect() in wamp

wordpress - wamp 上的多站点无法在第一次点击时创建新站点

php - 在命令行上使用 EASYPHP DEVSERVER 访问 mySQL

javascript - 将 PX 的宽度转换为 % 但保持文本内容的比例

php - mysql语句中的组子查询计数?

当视频在 KitKat 上结束时,Android WebView 崩溃

android - 如何清除 android marshmallow 中的浏览历史记录