将图像从Android发送到PHP

时间:2017-08-09 13:17:10

标签: android

我尝试了3种不同的方法,用于将图像从Android发送到PHP。 这三个都给出了消息"缺少inp_image名称"。我想我可能不会将图像作为图像发送,而是作为一些文本发送? 我在Android中使用此http请求类:https://github.com/kevinsawicki/http-request

方法1,将其编码为base64:

                //String selectedFilePath = FilePath.getPath(context, imageUri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap bm = BitmapFactory.decodeFile(destImage,options);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
            byte[] byteImage_photo = baos.toByteArray(); // bitmap object

            //generate base64 string of image
            String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

            // Send image
            HttpRequest request = HttpRequest.post(apiUrl);
            request.part("inp_image", encodedImage);

            stringResponse = request.body();

方法2 - 发送图像输入流

        HttpRequest request = HttpRequest.post(apiUrl);
        request.part("inp_image", in); // sending input stream
        stringResponse = request.body();

方法3 - 发送文件:

  String sourceFilename= FilePath.getPath(context, imageUri);
            HttpRequest request = HttpRequest.post(apiUrl);
            request.part("inp_image", new File(sourceFilename)); // sending input stream
            stringResponse = request.body();

Android Mainifest:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

MainActivity:

    package com.nettport.imageupload.imageupload;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {


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

        /* Check permission */
        checkPermissionRead();
        checkPermissionWrite();

        /* Button listener */
        buttonListener();
    } // onCreate


    private void checkPermissionRead(){
        int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (shouldShowRequestPermissionRationale(
                    android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // Explain to the user why we need to read the contacts
            }

            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
            // app-defined int constant that should be quite unique

            return;
        }
    } // checkPermissionRead

    private void checkPermissionWrite(){
        int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (shouldShowRequestPermissionRationale(
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Explain to the user why we need to read the contacts
            }

            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
            // app-defined int constant that should be quite unique

            return;
        }
    } // checkPermissionRead

    public void buttonListener() {

        // Image button listener
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadImage);
        buttonLoadImage.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view){
                // Load gallery
                // User can select images and upload them
                // Result will be in onActivityResult
                Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

            }
        });
        // Camera
        Button buttonLoadCamera = (Button) findViewById(R.id.buttonLoadCamera);
        buttonLoadCamera.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view){
                // Load camera
                // Result will be in onActivityResult
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, 0);//zero can be replaced with any action code

            }
        });
    } // buttonListener


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();

            // Set image
            ImageView imageViewImage = (ImageView)findViewById(R.id.imageViewImage);
            imageViewImage.setImageURI(selectedImageUri);

            // Save image
            String destinationFilename = savefile(selectedImageUri);


            try {
                InputStream in = getContentResolver().openInputStream(selectedImageUri);

                TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
                String apiURL = "https://xxxxxx.com/xxxxxx/image_upload.php";

                UploadImage task = new UploadImage(this, apiURL, in, selectedImageUri, destinationFilename, textViewDynamicText, new UploadImage.TaskListener() {
                    @Override
                    public void onFinished(String result) {
                        // Do Something after the task has finished
                        imageUploadResult();
                    }
                });
                task.execute();

                //in.close();
            }
            catch (java.io.FileNotFoundException e) {
                Toast.makeText(this, "MainAcrivity java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
            }
            catch (java.io.IOException e) {
                Toast.makeText(this, "MainAcrivity java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
            }

        } // RESULT_OK
    } // onActivityResult


    public void imageUploadResult(){
        // Dynamic text
        TextView textViewDynamicText = (TextView)findViewById(R.id.textViewDynamicText);
        Toast.makeText(this, textViewDynamicText.getText().toString(), Toast.LENGTH_SHORT).show();

    } // imageUploadResult


    public String savefile(Uri sourceuri) {
        String sourceFilename= FilePath.getPath(this, sourceuri);
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Upload";
        String destinationFilename = destinationPath+"/upload_me.png";

        // Make dir
        File folder = new File(destinationPath);
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (success) {
        } else {
            Toast.makeText(this, "Dir failed", Toast.LENGTH_LONG).show();
        }


        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(sourceFilename));
           bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
            byte[] buf = new byte[1024];
            bis.read(buf);
            do {
                bos.write(buf);
            } while(bis.read(buf) != -1);
            // Toast.makeText(this, "Saved to " + destinationFilename, Toast.LENGTH_LONG).show();
        }
        catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "savefile#1: " + e.toString() + "\nFrom: " + sourceFilename, Toast.LENGTH_LONG).show();
        }
        finally {
            try {
                if (bis != null) bis.close();
                if (bos != null) bos.close();
            }
            catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "savefile#2: " + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
        return destinationFilename;
    }
}

UploadImage类:

package com.nettport.imageupload.imageupload;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by bruker on 08.08.2017.
 * Updated
 */

public class UploadImage extends AsyncTask<String, Void, String> {

    /* Class variables */
    private Context context; // Holder (this)
    private String  apiUrl; // URL for image upload form, example http://website.com/image_upload.php
    private TextView dynamicText;
    private InputStream in;
    private Uri imageUri;
    private String destImage;

    private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener


    public interface TaskListener {
        public void onFinished(String result);
    }

    /*- Constructor GET, SEND --------------------------------------------------------------- */
    public UploadImage(Context ctx, String applicationPIUrl, InputStream input, Uri selectedImageUri, String destinationFilename, TextView textViewDynamicText, UploadImage.TaskListener listener) {
        context             = ctx;
        apiUrl              = applicationPIUrl;
        in                  = input;
        imageUri            = selectedImageUri;
        destImage = destinationFilename;
        dynamicText         = textViewDynamicText;
        this.taskListener   = listener; // The listener reference is passed in through the constructor
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dynamicText.setText(dynamicText.getText().toString() + "\n" + "Loading...");
    }


    @Override
    protected String doInBackground(String... params) {
        // Run methods
        String stringResponse ="";
        try {
            try{

                // Method 1 - Base 64
                /*
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4;
                Bitmap bm = BitmapFactory.decodeFile(destImage,options);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
                byte[] byteImage_photo = baos.toByteArray(); // bitmap object

                //generate base64 string of image
                String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

                // Send image
                HttpRequest request = HttpRequest.post(apiUrl);
                request.part("inp_image", encodedImage);
                stringResponse = request.body();
                */



                // Method 2 - Input stream
                /*
                HttpRequest request = HttpRequest.post(apiUrl);
                request.part("inp_image", in); // sending input stream
                stringResponse = request.body();
                */


                // Method 3 - File
                String sourceFilename= FilePath.getPath(context, imageUri);
                HttpRequest request = HttpRequest.post(apiUrl);
                request.part("inp_image", new File(sourceFilename)); // sending input stream
                stringResponse = request.body();


            }
            catch (Exception e){
                return e.toString();
            }
        }
        catch(Exception e){
            return e.toString();
        }
        return stringResponse;
    }

    @Override
    protected void onPostExecute(String result) {
        // Set text view with result string
        if(dynamicText == null){
            Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
        }
        else {
            dynamicText.setText(dynamicText.getText().toString() + "\n" + result);
        }
        // In onPostExecute we check if the listener is valid
        if(this.taskListener != null) {
            // And if it is we call the callback function on it.
            this.taskListener.onFinished(result);
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {}

}

PHP脚本:

<?php
/**
*
* File: image_upload.php
* Date 13:05 04.08.2017
* Version 1
* Copyright (c) 2017 S. A. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/*- Get extention ---------------------------------------------------------------------- */
function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; } 
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
}

/*- Path -------------------------------------------------------------------------------- */
if(!(is_dir("_images"))){
    mkdir("_images");
}

/*- Script start ------------------------------------------------------------------------ */
$name = stripslashes($_FILES['inp_image']['name']);
if($name){
    $extension = getExtension($name);
    $extension = strtolower($extension);
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
        echo"unknown_file_extension";
    }
    else{
        $date_time = date("Y-m-d_h-i-s");
        $new_name = $date_time . ".png";
        $new_path = "_images/";
        $uploaded_file = $new_path . $new_name;

        // Upload file
        if (move_uploaded_file($_FILES['inp_image']['tmp_name'], $uploaded_file)) {
            // Get image size
            $file_size = filesize($uploaded_file);

            // Check with and height
            list($width,$height) = getimagesize($uploaded_file);

            if($width == "" OR $height == ""){
                echo"getimagesize_failed";
            }
            else{
                // Resize to $settings_image_width
                $newwidth=1000;
                $newheight=($height/$width)*$newwidth; // 667
                $tmp=imagecreatetruecolor($newwidth,$newheight);

                if($extension=="jpg" || $extension=="jpeg" ){
                    $src = imagecreatefromjpeg($uploaded_file);
                }
                else if($extension=="png"){
                    $src = imagecreatefrompng($uploaded_file);
                }
                else{
                    $src = imagecreatefromgif($uploaded_file);
                }

                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);


                imagepng($tmp,$uploaded_file);

                imagedestroy($tmp);

                echo"$new_name";
            } // width height
        } // move_uploaded_file
        else{
            switch ($_FILES['inp_food_image_b']['error']) {
                case UPLOAD_ERR_OK:
                    echo"image_to_big";
                    break;
                case UPLOAD_ERR_NO_FILE:
                        echo"no_file_uploaded";
                    break;
                case UPLOAD_ERR_INI_SIZE:
                        echo"to_big_size_in_configuration";
                    break;
                case UPLOAD_ERR_FORM_SIZE:
                        echo"to_big_size_in_form";
                    break;
                default:
                        echo"unknown_error";
                    break;
            }   
        }
    } // extention
} // name
else{
    echo"Missing inp_image name";
}

?>

1 个答案:

答案 0 :(得分:1)

尝试这个,它对我有用,

String imgstring = getStringImage(bitmap)



 public String getStringImage(Bitmap bmp) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            return encodedImage;
    }

凌空

public void addimage() {
        String link = CommonVariables.SERVER_IP + "/uploadimage.php";

        StringRequest request = new StringRequest(Request.Method.POST, link, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if (volleyError != null && volleyError.getMessage() != null) {
                    Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();

                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
             params.put("imagename", "yourimagename");
                params.put("imagecode", imageString);
                return params;
            }
        };

        RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        request.setRetryPolicy(mRetryPolicy);

        queue.add(request);
    }

PHP

<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){


 $imgcode = $_POST['imagecode'];
 $imagename = $_POST['imagename'];


 require_once('dbconnect.php');

 // this is ths path where your image is stored in the file in server
 $path = "images/$imagename.jpg";

 $sql = "INSERT INTO productlist(proimagename) 
         VALUES ('$imagename')";

 if(mysqli_query($con,$sql)){
 file_put_contents($path,base64_decode($imgcode));
 echo "1";
 }

 mysqli_close($con);
 }else{
 echo "0";
 }