簡體   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