使用base64字符串上传图像,导致图像损坏

时间:2015-12-27 04:26:53

标签: java android

我使用base64对图像进行编码,然后发送到php服务器。 它上传成功但导致图像损坏。 没有错误只有黑色图像。可能是我错过了一些重要的设置?

上传活动

package xxxx.com.myapps;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;

public class UploadImageActivity extends Activity {
    private Button btnBrowse, btnUpload;
    private AlertDialog.Builder dialogBuilder;
    private ImageView imageToUpload;
    private String imgPath, fileName;
    String encodedString;

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


        btnBrowse = (Button) findViewById(R.id.btnBrowse);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        imageToUpload = (ImageView) findViewById(R.id.imageToUpload);

        btnBrowse.setOnClickListener(btnListener);
        btnUpload.setOnClickListener(btnListener);
    }

    private Button.OnClickListener btnListener = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnBrowse:
                    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(galleryIntent, Constants.PICK_IMAGE_CONTACT_REQUEST);
                    break;
                case R.id.btnUpload:
                    Network network = new Network(UploadImageActivity.this);
                    if (network.isConnected()) {
                        new UploadImageAsyntask().execute();
                    } else {
                        dialogBuilder.setTitle(R.string.waring).setMessage(R.string.no_network_connection);
                        dialogBuilder.create();
                        dialogBuilder.show();
                    }
                    break;
            }
        }
    };


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            // When an Image is picked
            if (requestCode == Constants.PICK_IMAGE_CONTACT_REQUEST && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                // Set the Image in ImageView
                imageToUpload.setImageBitmap(BitmapFactory
                        .decodeFile(imgPath));
                // Get the Image's file name
                String fileNameSegments[] = imgPath.split("/");
                fileName = fileNameSegments[fileNameSegments.length - 1];
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
    }

    private class UploadImageAsyntask extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            Bitmap bitmap;
            bitmap = BitmapFactory.decodeFile(imgPath);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            encodedString = Base64.encodeToString(byteArray,0);

            String postParams = "tag=upload_new&filename=" + fileName + "&image=" + encodedString;
            String jsonResult = Network.webRequest(Constants.RENOTE_DB_URL, postParams);

            return jsonResult;
        }

        @Override
        protected void onPostExecute(String jsonResult) {
            super.onPostExecute(jsonResult);
            // Log.d("testing", jsonResult);
        }
    }
}

Http Request class

package xxxx.com.myapps;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class Network {
    Context context;

    public Network(Context context) {
        this.context = context;
    }

    public boolean isConnected() {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        return isConnected;
    }


    public static final String webRequest(String url, String postParams) {
        String requestResult = null;
        HttpURLConnection conn = null;
        try {
            URL remoteDbUrl = new URL(url);
            conn = (HttpURLConnection) remoteDbUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setUseCaches(false);

            if (postParams != null) {
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(postParams.getBytes());
                outputStream.close();
            }

            BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(conn.getInputStream())));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return requestResult;
    }
}

php上传代码 ...

else if ($tag == 'upload_new') {
        // Get image string posted from Android App
        $base = $_REQUEST['image'];
        // Get file name posted from Android App
        $filename = $_REQUEST['filename'];
        // Decode Image
        $binary = base64_decode($base);
        header('Content-Type: bitmap; charset=utf-8');

        $file = fopen('uploadedimages/' . $filename, 'wb');
        // Create File
        $result = fwrite($file, $binary);
        if ($result) {
            echo "success";
        } else {
            echo "fail";
        }
        fclose($file);
    } 

0 个答案:

没有答案