繁体   English   中英

Base64解码将Android转换为PHP

[英]Base64 Decoding Issues Android to PHP

我无法正确解码甚至编码文件。 我正在尝试通过排球将图像从android设备发送到php服务器。 我可以从php生成图像文件,但它显示为损坏,并且根本不显示图像。 这是我来自android的代码。

//Send image to server

            String url = "http://www.urlhere.com/test.php";

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);


                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();

                final String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

                StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
                                    String site = jsonResponse.getString("site"),
                                            network = jsonResponse.getString("network");
                                    System.out.println("Site: " + site + "\nNetwork: " + network);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                error.printStackTrace();
                            }
                        }
                ) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<>();
                        // the POST parameters:
                        params.put("picture", encoded);
                        return params;
                    }
                };
                Volley.newRequestQueue(getApplicationContext()).add(postRequest);

            } catch (IOException e) {
                e.printStackTrace();
            }


        }

这是PHP的一面,首先将其发送到php页面,将字符串放入文本文件中,然后使用此代码尝试将其转换为图像文件。

$file = file_get_contents('test.txt', true);

$filePath = "file.jpg";
$myfile = fopen($filePath, "w") or die("Unable to open file!");

file_put_contents($filePath, base64_decode($file));

现在,当创建文本文件时,它将picture =添加到基本64字符串的开头,并在末尾添加一个&符号。 我现在手动删除这两个字符串,以便对字符串进行解码,但是没有运气。

请帮帮我,我真的很感激。 谢谢。

更新

这是更新的代码,我使用的仍然无法正常工作。

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.Image;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class showImage extends AppCompatActivity {

ImageView imageView;
ImageButton imageButton;
String encodedString;
String fileName;

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

    imageView = (ImageView)findViewById(R.id.imageView);

    final Uri selectedImage = getIntent().getData();


    Glide.with(this).load(selectedImage).fitCenter().into(imageView);

    imageButton = (ImageButton)findViewById(R.id.imageButton);

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            String fileNameSegments[] = picturePath.split("/");
            fileName = fileNameSegments[fileNameSegments.length - 1];

            Bitmap myImg = BitmapFactory.decodeFile(picturePath);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            myImg.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
            // Encode Image to String
            encodedString = Base64.encodeToString(byte_arr, 0);

            uploadImage();




        }
    });

}

public void uploadImage() {

    RequestQueue rq = Volley.newRequestQueue(getApplicationContext());
    String url = "http:/www.testurl.com/test.php";
    Log.d("URL", url);
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                Log.e("RESPONSE", response);
                JSONObject json = new JSONObject(response);

                Toast.makeText(getBaseContext(),
                        "The image is upload", Toast.LENGTH_SHORT)
                        .show();

            } catch (JSONException e) {
                Log.d("JSON Exception", e.toString());
                Toast.makeText(getBaseContext(),
                        "Error while loadin data!",
                        Toast.LENGTH_LONG).show();
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("ERROR", "Error [" + error + "]");
            Toast.makeText(getBaseContext(),
                    "Cannot connect to server", Toast.LENGTH_LONG)
                    .show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put("image", encodedString);
            params.put("filename", fileName);

            return params;

        }

    };
    rq.add(stringRequest);
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_show_image, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

考虑到您不是为此目的而使用Web服务器而是VPS,请尝试本教程,我自己尝试了一下,它的工作原理很吸引人。 这也使用Volley:

http://team.158ltd.com/2015/04/30/how-to-upload-image-to-php-server-android/

如果问题仍然存在,我们将在评论中进行讨论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM