我无法正确解码或甚至编码文件。我试图通过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);
}
}