如何拍照并发送到WAMP服务器

时间:2019-01-07 03:49:35

标签: android

我想发送数据(拍摄的照片到wampserver)。如何运作?

public class MainActivity extends Activity {
ImageView picture;
Button button;
static  final int CAM_REQUEST = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button takePicture = (Button) findViewById(R.id.button);
    ImageView picture = (ImageView) findViewById(R.id.imageView);

    takePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = getfile();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            //startActivityForResult(intent, 0);
            startActivityForResult(intent, CAM_REQUEST);
        }
    });

}

private File getfile()
{
    File folder = new File ("localhost:8080/sampleTest.php");
    if (!folder.exists())
    {
        folder.mkdir();
    }
    File image_file = new File(folder, "cam_image.jpg");
    return image_file;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    //Bitmap bitmap = (Bitmap)data.getExtras().get("data");
    //picture.setImageBitmap(bitmap);

    String path = "localhost:8080/sampleTest.php/cam_image.jpg";
    picture.setImageDrawable(Drawable.createFromPath(path));

}
}

我希望输出能够拍照。拍照后,将图片发送到“ localhost:8080 / sampleTest.php”。但是,我得到的是我只能拍照,无法将图片发送到wampserver。

1 个答案:

答案 0 :(得分:0)

有意调用相机应用程序

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

获取从相机返回的缩略图:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
    Bundle extras = data.getExtras();
    Bitmap imageBitmap = (Bitmap) extras.get("data");
    mImageView.setImageBitmap(imageBitmap);
}}

如果要获得质量更好的图像,则需要提供相机应用程序的图像保存路径。

因此,将权限添加到AndroidManifest.xml

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

改善意图:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
Intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, 0);

返回结果时解码图像文件:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
        setPic();
    }}


private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();

// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;

Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);}

从Android客户端到服务器的图像传输

现在,我们可以结合使用两种功能来增强Android应用程序。 要访问Internet,请向AndroidManifest.xml添加以下权限:

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

请参考this blog,创建一个类MultipartEntity:

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds(){
    if(!isSetFirst){
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if(isSetLast){
        return ;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {

    }
}

public void addPart(final String key, final String fileName, final InputStream fin){
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName, final InputStream fin, String type){
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: "+type+"\r\n";
        out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

@Override
public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

@Override
public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}

@Override
public boolean isChunked() {
    return false;
}

@Override
public boolean isRepeatable() {
    return false;
}

@Override
public boolean isStreaming() {
    return false;
}

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

@Override
public Header getContentEncoding() {
    return null;
}

@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
        "Streaming entity does not implement #consumeContent()");
    }
}

@Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}}

使用AsyncTask处理上传工作:

private class UploadTask extends AsyncTask<Bitmap, Void, Void> {

    protected Void doInBackground(Bitmap... bitmaps) {
        if (bitmaps[0] == null)
            return null;

        Bitmap bitmap = bitmaps[0];
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
        InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost(
                    "http://192.168.8.84:8003/savetofile.php"); // server

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("myFile",
                    System.currentTimeMillis() + ".jpg", in);
            httppost.setEntity(reqEntity);

            Log.i(TAG, "request " + httppost.getRequestLine());
            HttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if (response != null)
                    Log.i(TAG, "response " + response.getStatusLine().toString());
            } finally {

            }
        } finally {

        }

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
    }
}
相关问题