gpt4 book ai didi

php - 将图像发送到服务器需要很多时间

转载 作者:行者123 更新时间:2023-11-29 21:19:14 25 4
gpt4 key购买 nike

在我的 android 应用程序中,我试图将捕获的图像从相机发送到我的 php 服务器。有时图像成功发送到服务器或有时发送到服务器失败。我认为图像没有发送到服务器,因为它需要很多时间。那么我该如何解决这个问题,请指导我。我在此处附上了完整的源代码。

public class MainActivity extends Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Bitmap bitmap;
ProgressDialog pd;
InputStream is;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

private Uri fileUri; // file url to store image/video

private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo,upload;

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

imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button)findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
upload=(Button)findViewById(R.id.upload);

upload.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(bitmap==null)
{
Toast.makeText(getApplicationContext(), "Please Select Image",Toast.LENGTH_LONG).show();

}
else
{
new ImageUpload().execute();
}

}
});

/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// capture picture
captureImage();
}
});

/*
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// record video
recordVideo();
}
});

// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}

/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}

/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

// start the image capture Intent
startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/*
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);

// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}

/*
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);

intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name

// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}

/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);

imgPreview.setVisibility(View.VISIBLE);
upload.setVisibility(View.VISIBLE);

// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();

// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;

bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);

imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}

/*
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);

videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* ------------ Helper Methods ----------------------
* */

/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}

/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {

// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);

// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}

// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}

return mediaFile;
}

public class ImageUpload extends AsyncTask<String, String,String>
{
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("Please Wait Image is Uploading");
pd.setCancelable(false);
pd.show();


}

@Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

byte [] ba = bao.toByteArray();

String ba1=Base64.encodeToString(ba,1);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("image",ba1));

try
{

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://192.168.1.86/camera/upload.php");

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

//Toast.makeText(SignUpActivity.this, "Joining Failed", Toast.LENGTH_SHORT).show();

}
catch(Exception e)
{

Log.e("log_tag", "Error in http connection "+e.toString());
}

return null;
}

@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "Image Successfully Uploaded",Toast.LENGTH_LONG).show();
pd.dismiss();
}



}
}

这是 list 文件公共(public)类 MainActivity 扩展 Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Bitmap bitmap;
ProgressDialog pd;
InputStream is;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

private Uri fileUri; // file url to store image/video

private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo,upload;

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

imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button)findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
upload=(Button)findViewById(R.id.upload);

upload.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(bitmap==null)
{
Toast.makeText(getApplicationContext(), "Please Select Image",Toast.LENGTH_LONG).show();

}
else
{
new ImageUpload().execute();
}

}
});

/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// capture picture
captureImage();
}
});

/*
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// record video
recordVideo();
}
});

// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}

/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}

/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

// start the image capture Intent
startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/*
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);

// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}

/*
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);

intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name

// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}

/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);

imgPreview.setVisibility(View.VISIBLE);
upload.setVisibility(View.VISIBLE);

// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();

// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;

bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);

imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}

/*
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);

videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* ------------ Helper Methods ----------------------
* */

/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}

/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {

// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);

// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}

// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}

return mediaFile;
}

public class ImageUpload extends AsyncTask<String, String,String>
{
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("Please Wait Image is Uploading");
pd.setCancelable(false);
pd.show();


}

@Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

byte [] ba = bao.toByteArray();

String ba1=Base64.encodeToString(ba,1);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("image",ba1));

try
{

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://192.168.1.86/camera/upload.php");

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

//Toast.makeText(SignUpActivity.this, "Joining Failed", Toast.LENGTH_SHORT).show();

}
catch(Exception e)
{

Log.e("log_tag", "Error in http connection "+e.toString());
}

return null;
}

@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "Image Successfully Uploaded",Toast.LENGTH_LONG).show();
pd.dismiss();
}



}

}这是 list 文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.androidcameraapi"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<!-- Accessing camera hardware -->
<uses-feature android:name="android.hardware.camera" />

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="info.androidhive.androidcameraapi.MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboard|keyboardHidden"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

这是服务端代码

<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';?>

最佳答案

我的建议是使用

HttpURLConnection

上传,只是作为一个例子看看下面的代码并尝试相应地修改。

Uploading files to HTTP server using POST on Android.

http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

关于php - 将图像发送到服务器需要很多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20947079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com