Base64解码问题Android到PHP


Base64 Decoding Issues Android to PHP

我有问题的文件被正确解码,甚至可能编码。我试图发送一个图像到一个php服务器通过凌空从android设备。我能够从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/

如果问题仍然存在,我们将在注释中讨论。祝你好运!