захватить изображение с камеры и отправить его непосредственно на сервер

Я пытаюсь написать небольшой код, который позволяет мне отправлять изображение сразу после его съемки с камеры, я имею в виду, когда я делаю снимок с камеры, это изображение будет отправлено непосредственно на сервер без сохранения в моем телефоне или в SD-карта, поэтому я сделал этот код, но я не знаю, правильно ли он, потому что на самом деле он показывает мне много сообщений об ошибках, но я не знаю, в чем проблема или кто-нибудь может сказать мне, где я могу найти аналогичный код,

// Upload Direct From Camera
camButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent_gallery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent_gallery.putExtra( MediaStore.EXTRA_OUTPUT, SERVER_URL + "uploadFromCamera.php" );
        startActivityForResult(intent_gallery, SELECT_IMAGE);
    }
});
...

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            Uri selectedImageUri       = data.getData();
            String selectedImagePath   = getPath( selectedImageUri );
            String url                 = SERVER_URL + "uploadFromCamera.php";

            if ( selectedImagePath != null ) {
                //Send to server
            }
        }
    }           
}

public String getPath(Uri uri) {
    String result = null;
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if(cursor.moveToFirst()){;
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       result = cursor.getString(column_index);
    }
    cursor.close();
    return result;
}

person theo theo    schedule 04.01.2014    source источник
comment
Не могли бы вы опубликовать полученную ошибку/LogCat?   -  person hichris123    schedule 05.01.2014
comment
-Сбой доставки результата ResultInfo{ request=1, result=-1, data=Intent} для действия   -  person theo theo    schedule 05.01.2014
comment
...Вызвано NullPointerException в...(эта строка: курсор курсора = getContentResolver().query(uri, проекция, null, null, null);)   -  person theo theo    schedule 05.01.2014
comment
Не похоже, что вы определяете uri.   -  person hichris123    schedule 05.01.2014
comment
Я проверяю его снова, но он пуст. Почему?   -  person theo theo    schedule 05.01.2014


Ответы (4)


Этот код помогает загрузить изображение на сервер TomCat.

Android-приложение

    import java.io.ByteArrayOutputStream;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import android.support.v7.app.ActionBarActivity;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.util.Base64;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.Toast;

    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.RequestParams;


@SuppressLint("NewApi")
public class MainActivity extends Activity {
    ProgressDialog prgDialog;
    String encodedString;
    RequestParams params = new RequestParams();
    String imgPath, fileName;
    Bitmap bitmap, lesimg;
    private static int RESULT_LOAD_IMG = 1;
    private static int REQUEST_IMAGE_CAPTURE = 1;
    private static String TIME_STAMP="null";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prgDialog = new ProgressDialog(this);

        prgDialog.setCancelable(false);
    }

    public void loadImagefromGallery(View view) {

        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    public void dispatchTakePictureIntent(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ImageView imgView = (ImageView) findViewById(R.id.imgView);
            imgView.setImageBitmap(imageBitmap);
            lesimg=imageBitmap;
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

            String hjkl=currentDateTimeString.replaceAll(" ", "_");
            String hiop=hjkl.replaceAll(":", "-");
            TIME_STAMP=hiop;
            fileName=TIME_STAMP+".jpeg";
            params.put("filename", fileName);
        }
    }


    public void uploadImage(View v) {
        encodeImagetoString();

    }


    public void encodeImagetoString() {
        new AsyncTask<Void, Void, String>() {

            protected void onPreExecute() {

            };

            @Override
            protected String doInBackground(Void... params) {
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;

                bitmap=lesimg;
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream); 
                byte[] byte_arr = stream.toByteArray();

                encodedString = Base64.encodeToString(byte_arr, 0);
                return "";
            }

            @Override
            protected void onPostExecute(String msg) {
                prgDialog.setMessage("Calling Upload");
                prgDialog.show();

                params.put("image", encodedString);

                triggerImageUpload();
            }
        }.execute(null, null, null);
    }

    public void triggerImageUpload() {
        makeHTTPCall();
    }

    public void makeHTTPCall() {
        prgDialog.setMessage("Invoking JSP");   
        prgDialog.show();
        AsyncHttpClient client = new AsyncHttpClient();

        client.post("http://Your Ip Address or Localhost:8080/ImageUploadWebApp/uploadimg.jsp",
                params, new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String response) {

                        prgDialog.hide();
                        Toast.makeText(getApplicationContext(), response,
                                Toast.LENGTH_LONG).show();
                    }


                    @Override
                    public void onFailure(int statusCode, Throwable error,
                            String content) {

                        prgDialog.hide();

                        if (statusCode == 404) {
                            Toast.makeText(getApplicationContext(),
                                    "Requested resource not found",
                                    Toast.LENGTH_LONG).show();
                        }

                        else if (statusCode == 500) {
                            Toast.makeText(getApplicationContext(),
                                    "Something went wrong at server end",
                                    Toast.LENGTH_LONG).show();
                        }

                        else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                            + statusCode, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if (prgDialog != null) {
            prgDialog.dismiss();
        }
    }
}

XML-файл для Android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="dispatchTakePictureIntent"
        android:text="Click Picture" >
    </Button>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:onClick="uploadImage"
        android:text="Upload" />

</LinearLayout>

Серверная часть Создайте динамический веб-проект в Eclipse и запустите его с помощью сервера TomCat.

Веб-приложение

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.codec.binary.Base64;






public class ManipulateImage {
     public static byte[] convertStringtoImage(String encodedImageStr,    String fileName) {
         byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);
            try {

                 // URL url = new URL("http://www.amrood.com/index.htm?language=en#j2se");

                imageByteArray = Base64.decodeBase64(encodedImageStr); 

                // Write Image into File system - Make sure you update the path
                FileOutputStream imageOutFile = new FileOutputStream("C:/Some file Path" + fileName);
                imageOutFile.write(imageByteArray);

                imageOutFile.close();

                System.out.println("Image Successfully Stored");
            } catch (FileNotFoundException fnfe) {
                System.out.println("Image Path not found" + fnfe);
            } catch (IOException ioe) {
                System.out.println("Exception while converting the Image " + ioe);
            }
            return imageByteArray;

        }
     public static String[]  display(){

         File folder = new File("C:/Some file Path");
         File[] listOfFiles = folder.listFiles();
         String [] k = new String[listOfFiles.length];
         Arrays.fill(k,"none");

             for (int i = 0; i < listOfFiles.length; i++) {
               if (listOfFiles[i].isFile()) {
                 System.out.println("File " + listOfFiles[i].getName());
                 k[i]="File " + listOfFiles[i].getName();
               } else if (listOfFiles[i].isDirectory()) {
                 System.out.println("Directory " + listOfFiles[i].getName());
               }

             }
             return k;
     }

}

Сервлет

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayImageServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
String image_name = "";
ResourceBundle props = null;
String filePath = "";
private static final int BUFSIZE = 100;
private ServletContext servletContext;
public DisplayImageServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FROM SERVLET");
sendImage(getServletContext(), request, response);
}
public void sendImage(ServletContext servletContext,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.servletContext = servletContext;
String reqUrl = request.getRequestURL().toString();
StringTokenizer tokens = new StringTokenizer(reqUrl, "/");
int noOfTokens = tokens.countTokens();
String tokensString[] = new String[noOfTokens];
int count = 0;
while (tokens.hasMoreElements()) {
tokensString[count++] = (String) tokens.nextToken();
}
String folderName = tokensString[noOfTokens - 2];
image_name = tokensString[noOfTokens - 1];
filePath = "/" + folderName + "/" + image_name;
String fullFilePath = "D:/AndroidStudioProjects" + filePath;
System.out.println("FULL PATH :: "+fullFilePath);

doDownload(fullFilePath, request, response);
}
private void doShowImageOnPage(String fullFilePath,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.reset();
response.setHeader("Content-Disposition", "inline");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
response.setContentType("image/tiff");
byte[] image = getImage(fullFilePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);
outputStream.close();
}
private void doDownload(String filePath, HttpServletRequest request,
HttpServletResponse response) throws IOException {
File fileName = new File(filePath);
int length = 0;
ServletOutputStream outputStream = response.getOutputStream();

ServletContext context = servletContext;
String mimetype = context.getMimeType(filePath);
response.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
response.setContentLength((int) fileName.length());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ image_name + "\"");
byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outputStream.write(bbuf, 0, length);
}
in.close();
outputStream.flush();
outputStream.close();
}
private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
}

Поместите этот Jsp в веб-контент

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
    String imgEncodedStr = request.getParameter("image");
String fileName = request.getParameter("filename");
System.out.println("Filename: "+ fileName);
if(imgEncodedStr != null){
     response.setIntHeader("Refresh", 1);
     byte[] imageByteArray=( ManipulateImage.convertStringtoImage(imgEncodedStr, fileName));//edited

    System.out.println("Inside if");
    out.print("Image upload complete, Please check your directory");
} else{
    System.out.println("Inside else");
    out.print("Image is empty");    
}
%>

Вы можете увидеть загруженное изображение в указанной папке.

person Leslie Correa    schedule 10.09.2015

это пример кода для загрузки изображения на сервер PHP:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case 1:
            if(data != null && data.getData() != null){
                Uri _uri = data.getData();

                if (_uri != null) {
                    Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                    cursor.moveToFirst();
                    final String imageFilePath = cursor.getString(0);
                    Log.w("","image url : "+imageFilePath);
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            UploadFile upload = new UploadFile(UserID.getText().toString(), SignUp.this);
                            upload.uploadFile(imageFilePath);

                        }
                    }).start();
                    innitSignUp();
                }
            }

            break;

        default:
            break;
        }

////------------ код загружаемого файла:

public class UploadFile {
    private String upLoadServerUri = null;
    String t_name;
    Context context;

    public UploadFile(String filepath, Context context) {
        t_name = filepath;
        this.context = context;
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;
        int serverResponseCode = 200;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            return 0;
        } else {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                upLoadServerUri = context.getString(R.string.httpUploadImage);

                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename="+"'"
                 + t_name + ".jpg'" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                // close the streams
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

            } // End else block
        }
        return serverResponseCode;
    }



}
person Nguyen Thanh An    schedule 05.01.2014
comment
проблема в том, что после того, как я снова проверю свой код, он показывает, что uri пуст, почему? может быть, потому что я поместил ссылку на свою php-страницу в намерение_gallery.putExtra (MediaStore.EXTRA_OUTPUT, SERVER_URL + uploadFromCamera.php);? или это нормально так - person theo theo; 05.01.2014

При использовании этого метода с периметром прохода и именем файла необходимо установить username.jpg «формат изображения, такой как .png/.jpg»

public static String mediaFileUriString(Context context, Uri finalPicUri, 
String filename) {

        try {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = context.getContentResolver().query(finalPicUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            return picturePath;
        } catch (Exception e) {
            return AppConstant.storagePath.getAbsolutePath().concat("/").concat(filename);
        }
    }
person vishal panchal    schedule 25.12.2018

Я сделал это руководство, надеюсь, оно поможет, я использую Retrofit, чтобы отправить его на сервер.

    private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
                    "com.example.cedancp.uploadimage",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, MainActivity.RC_CAPTURE_IMAGE);
        }
    }
}


private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
);

currentImagePath = image.getPath(); //Save current image path to send later to server
return image;

}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
    switch (requestCode) {
            case RC_CAPTURE_IMAGE:
                Log.i(TAG, "RESULT CODE " + resultCode);
                if (resultCode == RESULT_OK) {
                    if(currentImagePath.length() > 0)
                    sendImageToServer(currentImagePath);
                }else{
                    currentImagePath = "";
                    Toast.makeText(MainActivity.this,"Error capturing image",Toast.LENGTH_SHORT).show();
                }
                break;
 default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void sendImageToServer(String imagePath, final boolean camera){
    final File image = new File(imagePath);
    if(image != null) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", image.getName(), requestFile);
        Call<JsonObject> call = api.uploadImage(body);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if(response.code() == 200){
                    Toast.makeText(MainActivity.this,"Image Uploaded!",Toast.LENGTH_SHORT).show();
                    if(camera){ //Delete image if it was taken from camera
                        image.delete(); 
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }
}

Раскрытие информации: это ссылка на мой собственный блог.

Учебник по загрузке изображения на сервер

person César Cobo    schedule 16.11.2017
comment
Ссылка на решение приветствуется, но убедитесь, что ваш ответ полезен и без нее: добавьте контекст вокруг ссылки, чтобы другие пользователи иметь некоторое представление о том, что это такое и почему оно там, а затем процитировать наиболее релевантную часть страницы, на которую вы ссылаетесь, в случае, если целевая страница недоступна. Ответы, которые представляют собой не более чем ссылку, могут быть удалены. - person LW001; 16.11.2017
comment
Кроме того, если вы публикуете ссылку на свой собственный блог, пожалуйста, должным образом сообщайте об этом. - person Michael Dodd; 16.11.2017
comment
хорошо, я этого не знал, я отредактировал свой ответ с помощью кода, который я использовал @LW001 - person César Cobo; 16.11.2017
comment
@CésarCobo удивительно, хотя, пожалуйста, сообщите, что вы являетесь владельцем связанного веб-сайта, иначе это будет пометка о спаме, которой вы (и ваша учетная запись) действительно недовольны. - person LW001; 16.11.2017