android - 通过来自 Android 的 HTTP Post 请求发送 Base64 编码的图像

标签 android image post base64 http-post

我完全迷路了,我正在尝试通过 Android 应用程序将照片发送到 PHP 网页。

理论上一切都应该是正确的,但目标数据已损坏或我不知道的东西......

我可以获得发布数据,我尝试使用一个简单的字符串它工作正常但是对于一个大文件数据似乎已损坏。

public class EncodingAndSending extends Thread{
    ShareOnMyWebSiteActivity mycontext;
    ContentResolver cr;
    Uri uri;
    public Handler mainHandler,sHandler;

    public EncodingAndSending(ShareOnMyWebSiteActivity myctxt,Handler mainone,Uri URI,ContentResolver crr){
         mycontext=myctxt;
         cr=crr;
         uri=URI;
         mainHandler=mainone;
         this.start();
    }

        return buffer.toString().toUpperCase();    
      }

    public void run(){

        InputStream is=null;
        byte[] data=null;
        try {
            is = cr.openInputStream(uri);
             // Get binary bytes for encode
            data = getFileBytes(is);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String data_string=Base64.encodeToString(data,Base64.URL_SAFE);


        if(data_string!=""){
            SendRequest(data_string);
        }
        else{

        }

    }

public byte[] getFileBytes(InputStream ios) throws IOException {
            ByteArrayOutputStream ous = null;
            //InputStream ios = null;
            try {
                byte[] buffer = new byte[4096];
                ous = new ByteArrayOutputStream();
                //ios = new FileInputStream(file);
                int read = 0;
                while ((read = ios.read(buffer)) != -1)
                    ous.write(buffer, 0, read);
            } finally {
                try {
                    if (ous != null)
                        ous.close();
                } catch (IOException e) {
                    // swallow, since not that important
                }
                try {
                    if (ios != null)
                        ios.close();
                } catch (IOException e) {
                    // swallow, since not that important
                }
            }
            return ous.toByteArray();
        }


    private void SendRequest(String data_string){

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("xxxxx.php");

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("image", data_string));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            ResponseHandler<String> responseHandler=new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);


        } catch (Exception e) {
            // TODO Auto-generated catch block
        }       
    }

}

编辑:

这行得通。我可以编码、解码和预览图像。我没有使用 getBytes() 函数我不知道问题是否出自那里。

我会告诉你的。

    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_image);
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    FileInputStream in;
    BufferedInputStream buf;

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
    ContentResolver cr = getContentResolver();
    Bitmap bMap=null;
    try {
        InputStream is = cr.openInputStream(uri);

        bMap = BitmapFactory.decodeStream(is);

        if (is != null) {
        is.close();
        }
    } catch (Exception e) {
        Log.e("Error reading file", e.toString());
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);   
    byte[] b = baos.toByteArray();
    String data_string=Base64.encodeToString(b,Base64.DEFAULT);

    b=null;bMap=null;
    b=Base64.decode(data_string, Base64.DEFAULT);
    bMap=BitmapFactory.decodeByteArray(b, 0, b.length);
    image.setImageBitmap(bMap);

最佳答案

我编写了一个小应用程序,允许将手机摄像头拍摄的图像发送到数据库。这是我解决问题的方法...

public void writeCommentForRestaurant(int id, String comment, String author,
        Bitmap image) {

    if (image != null) {
        /* Get the image as string */
        // Normal
        ByteArrayOutputStream full_stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, full_stream);
        byte[] full_bytes = full_stream.toByteArray();
        String img_full = Base64.encodeToString(full_bytes, Base64.DEFAULT);
        // Thumbnail
        ByteArrayOutputStream thumb_stream = new ByteArrayOutputStream();
                    // The getScaledBitmap method only minimizes the Bitmap to a small icon!
        getScaledBitmap(image, 72).compress(Bitmap.CompressFormat.JPEG, 75,
                thumb_stream);
        byte[] thumb_bytes = thumb_stream.toByteArray();
        String img_thumbnail = Base64.encodeToString(thumb_bytes, Base64.DEFAULT);

        // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
        // Integer.toString(id), comment, author, img_thumbnail, img_full);
    } else {
        // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
        // Integer.toString(id), comment, author, null, null);
    }
}

HTTPWorker 只是一个构造 HTTP 方法的异步任务。

...
/* Add arguments */
arguments.add(new BasicNameValuePair("idrestaurant", params[0]));
arguments.add(new BasicNameValuePair("comment", params[1]));
arguments.add(new BasicNameValuePair("author", params[2]));
if (params.length > 3) {
  arguments.add(new BasicNameValuePair("image", params[3]));
  arguments.add(new BasicNameValuePair("bigimage", params[4]));
}
...

然后我像这样将它发送到服务器。

/**
* Executes a httppost to a server instance with the given POST arguments
* and returns a String response from the server.
*/
private String httppost(String url, ArrayList<NameValuePair> args) {
  /* Create the channel for communicaton */
  InputStream is = null;

  /* Send request to server */
  try {
    /* Create the POST */
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    /* Add the login information "POST" variables in the php */
    httppost.setEntity(new UrlEncodedFormEntity(args));

    /* Execute the http POST and get the response */
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
  } catch (Exception e) {
    Log.e(TAG, "Error in http connection " + e.toString());
    return null;
  }

  /* Read response from server */
  try {
    /* Read the response stream */
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "iso-8859-1"), 8);

    /* Copy the response to StringBuilder */
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    is.close();

    /* Return the response as string */
    return sb.toString();
  } catch (Exception e) {
    Log.e(TAG, "Error converting result " + e.toString());
    return null;
  }
}

关于android - 通过来自 Android 的 HTTP Post 请求发送 Base64 编码的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9506793/

相关文章:

php - 如何使用 PHP 从 Mysql 数据库获取结果创建多项选择 Android ListView ?

android - 自定义 ListView 组件

android - 使用 Android Camera Intent 从同一个按钮拍摄视频或静态图片

javascript - 创建一个带有背景图片的 Javascript 画廊

javascript - 图像源更改,jquery 在事件完成之前未完成

php-如何使用ajax发布值?

java - 在 xml 中创建的字符串数组与在 Java 类中初始化的字符串数组有什么区别

Android:如何将操作栏背景颜色更改为深蓝色?

ios - 为 POST 请求使用辅助函数

Angular 5 - HTTP Post x-www-form-urlencoded